6

C++中实现多线程安全的单体类

 3 years ago
source link: http://blog.kongfy.com/2014/10/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

十月 2014

十月 2014 发表了 1 篇文章

C++中实现多线程安全的单体类

最近看了一些算是比较高大上的C++代码,被内力震伤了,赶紧记录下来!最最基础的就是这个:单体类。单体是面向对象中一种非常流行的设计模式,C++的实现百度一下可以找到一坨,但这个稍稍有点特殊——多线程安全。

普通版本的单体类实现如下:

# Singleton.h
class Singleton  
public:  
    static Singleton * Instance();
    static bool IsCreated();
private:  
    //Singleton模式,隐藏构造函数  
    Singleton();  
    static Singleton * m_Instance;
# Singleton.cpp
#include "Singleton.h"
Singleton * Singleton::m_Instance = NULL;  
Singleton::Singleton()  
//返回Singleton的唯一实例  
Singleton * Singleton::Instance()  
    if (NULL == m_Instance) {  
        m_Instance = new Singleton();  
    return m_Instance;  
bool Singleton::IsCreated()
    return (NULL != m_Instance);

乍一看似乎完全没有问题,不过如果这个单体类运行在多线程环境中,将会有可能创建多个实例。临界区出现在Instance()函数中创建单体对象的部分,即静态变量m_Instance!当访问该变量判断单体是否已被创建时,如果不进行临界区保护,很有可能会造成多个线程同时进入临界区,创建了多个Singleton对象,Boom…

继续阅读:→

分类: C/C++ | 2014-10-06 | 297 个字 | 4 Comments


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK