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

Is Local Static Variable Initialization in C 11 Thread-Safe?

Mary-Kate Olsen
Release: 2024-12-29 11:23:09
Original
927 people have browsed it

Is Local Static Variable Initialization in C  11 Thread-Safe?

C 11 Local Static Variable Initialization: Thread Safety

Regarding the thread safety of local static variable initialization in C 11, there have been numerous discussions. This article aims to provide a comprehensive answer based on the current standard and implementation status.

C 11 Thread-Safety of Local Static Variables

Section 6.7 of the C 11 standard explicitly states that the initialization of a local static variable occurs the first time control passes through its declaration. Furthermore, the initialization is considered complete upon its completion, and any concurrent execution entering the declaration while initialization is underway must wait for its completion.

Implementation in Compilers

In compliance with the standard, popular compilers such as GCC 4.7, Visual C 2011, and Clang 3.0 have implemented thread-safe initialization for local static variables. This ensures that the constructor of a local static variable, such as lg in the example provided, will run only once, guaranteeing thread-safe initialization.

Additional Considerations

While the initialization is thread-safe, it is important to note that this does not extend to subsequent access to the variable through a reference. Therefore, it is still necessary to ensure thread safety in the usage of the initialized variable, as the standard does not specify any specific guarantees for thread-safe access beyond the initialization stage.

The above is the detailed content of Is Local Static Variable Initialization in C 11 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