efficient thread-safe singleton in C++

前端 未结 9 1563
醉话见心
醉话见心 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条回答
  • 2020-11-28 19:06

    Your alternative is called "double-checked locking".

    There could exist multi-threaded memory models in which it works, but POSIX does not guarantee one

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-28 19:08

    The solution is not thread safe because the statement

    inst = new Foo();
    

    can be broken down into two statements by compiler:

    Statement1: inst = malloc(sizeof(Foo));
    Statement2: inst->Foo();

    Suppose that after execution of statement 1 by one thread context switch occurs. And 2nd thread also executes the getInstance() method. Then the 2nd thread will find that the 'inst' pointer is not null. So 2nd thread will return pointer to an uninitialized object as constructor has not yet been called by the 1st thread.

    0 讨论(0)
提交回复
热议问题