Home >Backend Development >C++ >Is Meyers' Singleton Implementation Thread-Safe in Different C Standards?
Meyers' Singleton Implementation: Thread Safety in Different C Standards
Meyers' implementation of the Singleton pattern with lazy initialization poses questions about its thread safety. This article examines its behavior in different C standards.
C 11 and Later
In C 11 and subsequent standards, Meyers' Singleton implementation is thread-safe. According to the standard (§6.7 [stmt.dcl] p4), concurrent execution of the declaration must wait for initialization completion.
C 03
In C 03, Meyers' Singleton implementation was not thread-safe. Meyers' article on "Double-Checked Locking" highlights this issue. He suggests full locking around the instantiating method as a simple approach to ensure thread safety on all platforms. Double-checked locking patterns may be prone to race conditions on certain architectures without strategic memory barriers.
Supported Compilers
Dynamic Initialization and Destruction with Concurrency (Magic Statics on MSDN) is the underlying feature that ensures thread safety in C 11. The following compilers support this feature:
The above is the detailed content of Is Meyers' Singleton Implementation Thread-Safe in Different C Standards?. For more information, please follow other related articles on the PHP Chinese website!