Home > Backend Development > C++ > Is C 11's Static Local Variable Initialization Thread-Safe?

Is C 11's Static Local Variable Initialization Thread-Safe?

Susan Sarandon
Release: 2024-12-29 11:22:11
Original
495 people have browsed it

Is C  11's Static Local Variable Initialization Thread-Safe?

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template