Local Static Variable Initialization in C 11: Thread Safety
Question:
In C 11, does the constructor of a static local variable like the one in the example below run exactly once, even in multi-threaded scenarios?
Logger& g_logger() { static Logger lg; return lg; }
Answer:
According to the C 11 standard in section 6.7, a static local variable is initialized the first time control passes through its declaration. This initialization must complete before any concurrent execution can proceed. Furthermore, the implementation is prohibited from causing a deadlock during this initialization.
Compiler Implementations:
Current releases of popular compilers, including gcc 4.7, vc 2011, and clang 3.0, properly implement this thread-safe behavior. Therefore, you can be assured that the local static variable will be initialized once and only once, guaranteeing correct operation in multi-threaded scenarios.
Additional Notes:
It's important to note that while the initialization of the static local variable is thread-safe, subsequent access to the variable through a reference like lg may not be thread-safe unless additional synchronization measures are implemented.
The above is the detailed content of Is C 11's Static Local Variable Initialization Thread-Safe?. For more information, please follow other related articles on the PHP Chinese website!