efficient thread-safe singleton in C++

前端 未结 9 1618
醉话见心
醉话见心 2020-11-28 18:30

The usual pattern for a singleton class is something like

static Foo &getInst()
{
  static Foo *inst = NULL;
  if(inst == NULL)
    inst = new Foo(...);
         


        
9条回答
  •  旧时难觅i
    2020-11-28 19:08

    Your solution is called 'double checked locking' and the way you've written it is not threadsafe.

    This Meyers/Alexandrescu paper explains why - but that paper is also widely misunderstood. It started the 'double checked locking is unsafe in C++' meme - but its actual conclusion is that double checked locking in C++ can be implemented safely, it just requires the use of memory barriers in a non-obvious place.

    The paper contains pseudocode demonstrating how to use memory barriers to safely implement the DLCP, so it shouldn't be difficult for you to correct your implementation.

提交回复
热议问题