Thread Safety of Meyers' Singleton Pattern Implementation
This implementation of Meyers' Singleton pattern using lazy initialization raises questions about its thread safety.
Meyers' Singleton Implementation
The provided code for the Singleton pattern is as follows:
static Singleton& instance() { static Singleton s; return s; }
Thread Safety Analysis
In C 11, this implementation is thread safe due to the guarantee in §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."
Compilers like GCC (since version 4.3) and Visual Studio (since 2015) support this feature.
C 03 Implementation
In C 03, the code was not thread safe. Meyers' article "C and the Perils of Double-Checked Locking" discusses such concerns. Full locking around the instantiating method was recommended to guarantee concurrency, while double-checked locking variants might encounter race conditions on specific architectures without memory barriers.
The above is the detailed content of Is Meyers' Singleton Pattern Thread-Safe in C 11 and Later?. For more information, please follow other related articles on the PHP Chinese website!