efficient thread-safe singleton in C++

前端 未结 9 1602
醉话见心
醉话见心 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: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.

提交回复
热议问题