Home >Backend Development >C++ >Is Meyers' Singleton Implementation Thread-Safe in C 11?
Is Meyers' Singleton Design Thread-Safe?
The presented implementation of Meyers' Singleton pattern, using lazy initialization, raises the question of thread safety. Here's an analysis of why this code is thread-safe in C 11 and how it achieves thread safety.
Thread Safety in C 11
According to the C 11 standard, §6.7 [stmt.dcl] p4:
If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization.
This implies that in C 11, the above implementation becomes thread-safe. The standard requires that thread execution waits for the completion of initialization before accessing the variable, ensuring thread safety.
Support in Compilers
The following compilers provide support for Dynamic Initialization and Destruction with Concurrency, which enables this feature:
Note for C 03
In C 03, the code was not thread-safe. Meyers in his article, "C and the Perils of Double-Checked Locking," suggests that in C 03, full locking around the instantiating method is the most straightforward way to ensure thread safety across platforms.
The above is the detailed content of Is Meyers' Singleton Implementation Thread-Safe in C 11?. For more information, please follow other related articles on the PHP Chinese website!