Is the following implementation, using lazy initialization, of Singleton
(Meyers' Singleton) thread safe?
static Singleton& instance()
{
static Singleton s;
return s;
}
If not, why and how to make it thread safe?
In C++11, it is thread safe. According to the 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.
GCC and VS support for the feature (Dynamic Initialization and Destruction with Concurrency, also known as Magic Statics on MSDN) is as follows:
Thanks to @Mankarse and @olen_gam for their comments.
In C++03, this code wasn't thread safe. There is an article by Meyers called "C++ and the Perils of Double-Checked Locking" which discusses thread safe implementations of the pattern, and the conclusion is, more or less, that (in C++03) full locking around the instantiating method is basically the simplest way to ensure proper concurrency on all platforms, while most forms of double-checked locking pattern variants may suffer from race conditions on certain architectures, unless instructions are interleaved with strategically places memory barriers.