Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 Thread-safe initialization of function-local static const objects

This question has been asked in a C++98 context, and answered in that context, but nothing was clearly stated about C++11

const some_type& create_const_thingy()
{
    lock my_lock(some_mutex);
    static const some_type the_const_thingy;
    return the_const_thingy;
}

void use_const_thingy()
{
    static const some_type& the_const_thingy = create_const_thingy();

    // use the_const_thingy
}

Would this initialization pattern ensure that:

  1. No race condition occurs
  2. create_const_thingy is called only once
  3. Is this still valid if we remove the mutex lock?

Thanks in advance!

like image 581
galinette Avatar asked Feb 06 '23 17:02

galinette


1 Answers

Since C++11 all static local variables are guaranteed to be initialized only once in a thread-safe manner.

As per cppreference:

If multiple threads attempt to initialize the same static local variable concurrently, the initialization occurs exactly once (similar behavior can be obtained for arbitrary functions with std::call_once). Note: usual implementations of this feature use variants of the double-checked locking pattern, which reduces runtime overhead for already-initialized local statics to a single non-atomic boolean comparison.

So, for your questions:

  1. yes
  2. yes
  3. yes
like image 130
krzaq Avatar answered Feb 08 '23 06:02

krzaq