Home >Backend Development >C++ >Is C 11 Local Static Variable Initialization Guaranteed to be Thread-Safe?
One frequently debated question in C is the thread-safety of local static variable initialization, such as in the following code:
Logger& g_logger() { static Logger lg; return lg; }
In the C 11 standard, the behavior of such initializations has been finalized, and it is now guaranteed to be thread-safe. Section 6.7 of the standard specifies that "such a variable is initialized the first time control passes through its declaration," and that "concurrent execution shall wait for completion of the initialization." Additionally, an implementation footnote clarifies that "The implementation must not introduce any deadlock around execution of the initializer."
The major compilers (gcc 4.7, vc 2011, and clang 3.0) have implemented the revised thread-safety requirements correctly. This means that the constructor for the lg variable will be executed only once, even in the presence of concurrent threads.
Note that this guarantee only applies to the initialization itself. Subsequent access to the variable through the reference is not necessarily thread-safe.
The above is the detailed content of Is C 11 Local Static Variable Initialization Guaranteed to be Thread-Safe?. For more information, please follow other related articles on the PHP Chinese website!