Thread Safety of Local Static Variable Initialization in C 11
Question:
In C 11, is it guaranteed that the constructor of a local static variable like the one below will run only once in a multi-threaded context?
Logger& g_logger() { static Logger lg; return lg; }
Answer:
Yes, the constructor of lg is guaranteed to run only once.
The C 11 standard (section 6.7) states that a local static variable is initialized the first time control passes through its declaration, and such initialization is guaranteed to complete before any concurrent execution may proceed. Furthermore, the implementation is required to ensure that no deadlock can occur during initializer execution.
Therefore, in C 11, thread-safe initialization of local static variables is enforced by the standard.
Implementation Status:
The latest releases of popular compilers (including gcc 4.7, Visual C 2011, and Clang 3.0) have been verified to correctly implement the thread-safe initialization of local static variables as per the C 11 standard.
The above is the detailed content of Is C 11's Local Static Variable Initialization Thread-Safe?. For more information, please follow other related articles on the PHP Chinese website!