Thread safe singleton in C++

左心房为你撑大大i 提交于 2019-12-08 11:26:39

问题


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?


回答1:


Not a good idea. Look for double check locking. For instance:

http://www.drdobbs.com/cpp/c-and-the-perils-of-double-checked-locki/184405726

http://www.drdobbs.com/cpp/c-and-the-perils-of-double-checked-locki/184405772




回答2:


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.



来源:https://stackoverflow.com/questions/11921135/thread-safe-singleton-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!