Home >Backend Development >C++ >Is C 11 Local Static Variable Initialization Guaranteed to be Thread-Safe?

Is C 11 Local Static Variable Initialization Guaranteed to be Thread-Safe?

Linda Hamilton
Linda HamiltonOriginal
2024-12-25 06:45:10819browse

Is C  11 Local Static Variable Initialization Guaranteed to be Thread-Safe?

Guaranteed Thread-Safe Local Static Variable Initialization in C 11

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;
}

C 11 Standard and Thread Safety

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."

Compiler Implementation

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn