Home >Backend Development >C++ >Is Meyers' Singleton Implementation Thread-Safe in C 11 and C 03?
Thread Safety of Meyers' Singleton Implementation
In the provided Meyers' Singleton implementation with lazy initialization, the code is thread-safe in C 11. According to the C 11 standard (§6.7 [stmt.dcl] p4), if multiple threads attempt to access the Singleton during initialization, the other threads will wait until the initialization is complete.
GCC and Visual Studio both support this thread-safety feature (Dynamic Initialization and Destruction with Concurrency), though with different implementation dates:
In contrast, this code is not thread-safe in C 03. Meyers' article "C and the Perils of Double-Checked Locking" analyzes various thread-safe implementations of the Singleton pattern. Ultimately, Meyers concludes that (in C 03) using a full lock around the instantiation method is the most straightforward approach to ensure concurrency across different platforms. On the other hand, double-checked locking pattern variants may introduce race conditions on certain architectures unless memory barriers are strategically placed between instructions.
The above is the detailed content of Is Meyers' Singleton Implementation Thread-Safe in C 11 and C 03?. For more information, please follow other related articles on the PHP Chinese website!