Is Meyers' implementation of the Singleton pattern thread safe?

前端 未结 6 835
我寻月下人不归
我寻月下人不归 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:26

    Is the following implementation [...] thread safe?

    On most platforms, this is not thread-safe. (Append the usual disclaimer explaining that the C++ standard doesn't know about threads, so, legally, it doesn't say whether it is or not.)

    If not, why [...]?

    The reason it isn't is that nothing prevents more than one thread from simultaneously executing s' constructor.

    how to make it thread safe?

    "C++ and the Perils of Double-Checked Locking" by Scott Meyers and Andrei Alexandrescu is a pretty good treatise on the subject of thread-safe singletons.

提交回复
热议问题