简体   繁体   中英

Thread safe singleton in C++

I have been reading about thread safe singletons and the implementation I find everywhere has a getInstance() method something like this:

Singleton* getInstance()
{
    if ( !initialized )
    {
        lock();
        if ( !initialized )
        {
            instance = new Singleton();
            initialized = true;
        }
        unlock();
    }

    return instance;
}
  • Is this actually thread safe?
  • Have I missed something or is there a small chance this function will return an uninitialized instance because 'initialized' may be reordered and set before instance?

This article is on a slightly different topic but the top answer describes why I think the above code is not thread safe:

Why is volatile not considered useful in multithreaded C or C++ programming?

It is indeed not thread safe, because after the pointer gets returned you still work with it, although the mutex is unlocked again.

What you can do is making the child class which inherits from singleton, thread safe. Then you're good to go.

Below is the code for a thread-safe singleton, using Double Check and temporary variable. A temporary variable is used to construct the object completely first and then assign it to pInstance.

Singleton* Singleton::instance() {
   if (pInstance == 0) {
      Lock lock;
      if (pInstance == 0) {
         Singleton* temp = new Singleton; // initialize to temp
         pInstance = temp; // assign temp to pInstance
      }
   }
   return pInstance;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM