Meyers Singleton线程安全与C ++ - 98 [英] Meyers Singleton thread safe with C++-98

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

问题描述

目前我有这个meyer单例的实现:

Currently I have this implementation of the meyer singleton:

class ClassA
{
public:
    static ClassA& GetInstance()
    {                   
        static ClassA instance;     
        return instance;
    }   

private:
    ClassA::ClassA() {};

    // avoid copying singleton
    ClassA(ClassA const&);
    void operator = (ClassA const&);
};

现在我需要一些改进才能使这个代码线程安全在C ++ - 98和VS- 2008?

Now I need some improvements to getting this code thread safe in C++-98 and VS-2008?!

谢谢!

PS:什么不清楚?你看到标签visual-studio-2008和c ++ - 98 - >所以目标操作系统是Windows!我也不明白为什么我下来投票只有一些人不喜欢Singleton的所有!

PS: What is unclear? You see the tags visual-studio-2008 and c++-98 -> so the target OS is Windows! I also don't understand why I got down voted solely some people don't like Singleton's at all!

推荐答案

Meyer singleton一般不是最好的解决方案,而
尤其不是在多线程环境中。更一般的
实现单例的方式是:

The Meyer singleton isn't the best solution in general, and especially not in a multithreaded environment. A more general way of implementing a singleton would be:

class ClassA
{
    static ClassA* ourInstance;
    //  ctor's, etc.
public:
    static ClassA& instance();
};

并在源文件中:

ClassA* ClassA::ourInstance = &instance();

// This can be in any source file.
ClassA&
ClassA::instance()
{
    if ( ourInstance == NULL ) {
        ourInstance = new ClassA;
    }
    return *ourInstance;
}

这是线程安全的在进入
main (应该是这种情况)之前,它不是动态
加载(这也应该是case—到
是唯一的,并且可以从静态
对象的构造函数中访问,那么它必须是它们的静态构造函数
运行时)。它还具有避免任何顺序的
销毁问题的优点。

This is thread safe if no threads are created before entering main (which should be the case), and it is not dynamically loaded (which should also be the case—if the object is to be unique, and accessible from the constructors of static objects, then it has to be their when the static constructors run). It also has the advantage of avoiding any order of destruction problems.

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

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