Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is local static variable initialization thread-safe in C++11? [duplicate]

People also ask

Is static variable initialization thread safe?

[Note: After this article was written, the C++ standard has been revised. Starting in C++11, scoped static initialization is now thread-safe, but it comes with a cost: Reentrancy now invokes undefined behavior.]

Is static variable thread safe?

Static variables are not thread safe. Instance variables do not require thread synchronization unless shared among threads. But, static variables are always shared by all the threads in the process.

Can static variable be initialized twice?

@heksesang: Yes, it happens only in this constellation. If I make both A and B static libs or both shared libs, I do not face the issue (c'tor of A is run only once). However, I would expect the linker to recognize and eliminate duplicate symbols and init calls.


The relevant section 6.7:

such a variable is initialized the first time control passes through its declaration; such a variable is considered initialized upon the completion of its initialization. [...] If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization.

Then there's a footnote:

The implementation must not introduce any deadlock around execution of the initializer.

So yes, you're safe.

(This says nothing of course about the subsequent access to the variable through the reference.)


--fno-threadsafe-statics also worth mentioning. In gcc:

Do not emit the extra code to use the routines specified in the C++ ABI for thread-safe initialization of local statics. You can use this option to reduce code size slightly in code that doesn't need to be thread-safe.

Also, have a look at the old thread Are function static variables thread-safe in GCC?