线程安全单例在C ++中 [英] Thread safe singleton in C++

查看:178
本文介绍了线程安全单例在C ++中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读有关线程安全的单例,并且我发现遍历的实现有一个这样的getInstance()方法:

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;
}




  • 这个线程是否安全? >
  • 我错过了一些东西,还是有一个很小的机会,这个函数会返回一个未初始化的实例,因为初始化可能会在实例之前重新排序并设置

  • 这篇文章略有不同,但最重要的答案是为什么我认为上述代码不是线程安全的:

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

    < a href =http://stackoverflow.com/questions/2484980/why-is-volatile-not-considered-useful-in-multithreaded-c-or-c-programming>为什么volatile在多线程C中被认为是有用的或C ++编程?

    推荐答案

    不是一个好主意。寻找双重锁定。例如:

    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

    这篇关于线程安全单例在C ++中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆