Is Meyers' implementation of the Singleton pattern thread safe?

前端 未结 6 965
我寻月下人不归
我寻月下人不归 2020-11-22 04:55

Is the following implementation, using lazy initialization, of Singleton (Meyers\' Singleton) thread safe?

static Singleton& instance()
{
           


        
6条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 05:14

    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:

    • Visual Studio: supported since Visual Studio 2015
    • GCC: supported since GCC 4.3

    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.

提交回复
热议问题