C++线程安全的单例模式

在某些应用环境下面,一个类只允许有一个实例,这就是著名的单例模式。单例模式分为懒汉模式,跟饿汉模式两种。

1.饿汉模式的实现:

template <class T>
class singleton
{
    protected:    
        singleton(){};

    private:
        singleton(const singleton&){};//禁止拷贝
        singleton& operator=(const singleton&){};//禁止赋值
        static T* m_instance;

    public:
        static T* GetInstance();
};


template <class T>
T* singleton<T>::GetInstance()
{
    return m_instance;
}

template <class T>
T* singleton<T>::m_instance = new T();

在实例化m_instance 变量时,直接调用类的构造函数。顾名思义,在还未使用变量时,已经对m_instance进行赋值,就像很饥饿的感觉。这种模式,在多线程环境下肯定是线程安全的,因为不存在多线程实例化的问题。

2.懒汉模式的实现:

template <class T>
class singleton
{
    protected:    
        singleton(){};

    private:
        singleton(const singleton&){};
        singleton& operator=(const singleton&){};
        static T* m_instance;

    public:
        static T* GetInstance();
};


template <class T>
T* singleton<T>::GetInstance()
{
    if( m_instance == NULL)
    { 
        m_instance = new T();
    }
    return m_instance;
}

template <class T>
T* singleton<T>::m_instance = NULL;

懒汉模式下,在定义m_instance变量时先等于NULL,在调用GetInstance()方法时,在判断是否要赋值。这种模式,并非是线程安全的,因为多个线程同时调用GetInstance()方法,并且可能两个以上的线程同时进入了条件判断,就可能导致有产生多个实例。要实现线程安全,就必须加锁。

template <class T>
class singleton
{
    protected:    
        singleton(){};

    private:
        singleton(const singleton&){};
        singleton& operator=(const singleton&){};
        static T* m_instance;
        static pthread_mutex_t mutex;

    public:
        static T* GetInstance();
};


template <class T>
T* singleton<T>::GetInstance()
{
    pthread_mutex_lock(&mutex);
    if( m_instance == NULL)
    { 
        m_instance = new T();
    }
    pthread_mutex_unlock(&mutex);
    return m_instance;
}


template <class T>
pthread_mutex_t singleton<T>::mutex = PTHREAD_MUTEX_INITIALIZER;

template <class T>
T* singleton<T>::m_instance = NULL;

这一切看起来都很完美,但是程序猿是一种天生就不知道满足的动物。他们发现GetInstance()方法,每次进来都要加锁,会影响效率。然而这并不是必须的,于是又对GetInstance()方法进行改进:

template <class T>
T* singleton<T>::GetInstance()
{
    if( m_instance == NULL)
    {
        pthread_mutex_lock(&mutex);
        if( m_instance == NULL)
        { 
             m_instance = new T();
        }
        pthread_mutex_unlock(&mutex);
    }
    return m_instance;
}

这也就是所谓的“双检锁”机制。但是有人质疑这种实现还是有问题,在执行 m_instance = new T()时,可能 类T还没有初始化完成,m_instance 就已经有值了。这样会导致另外一个调用GetInstance()方法的线程,获取到还未初始化完成的m_instance 指针,如果去使用它,会有意料不到的后果。其实,解决方法也很简单,用一个局部变量过渡下即可:

template <class T>
T* singleton<T>::GetInstance()
{
    if( m_instance == NULL)
    {
        pthread_mutex_lock(&mutex);
        if( m_instance == NULL)
        { 
             T* ptmp = new T();
             m_instance = ptmp;
        }
        pthread_mutex_unlock(&mutex);
    }
    return m_instance;
}

注意:上面这里的讨论其实是有问题的,根本问题是new运算符何时返回的问题,是在类的构造函数没有执行完毕前就返回还是直到构造函数完全执行完毕后才返回,答案是后者。所以上面这一步是没有必要的,这里顺便附上new运算符的执行流程:

(1)通过operator new申请内存
(2)使用placement new调用构造函数(简单类型忽略此步)
(3)返回内存指针

到这里在懒汉模式下,也就可以保证线程安全了。

然而,在linux下面还有另一种实现。linux提供了一个叫pthread_once()的函数,它保证在一个进程中,某个函数只被执行一次。下面是使用pthread_once实现的线程安全的懒汉单例模式:

template <class T>
class singleton
{
    protected:    
        singleton(){};

    private:
        singleton(const singleton&){};
        singleton& operator=(const singleton&){};
        static T* m_instance;
        static pthread_once_t m_once;

    public:
        static void Init();
        static T* GetInstance();
};


template <class T>
void singleton<T>::Init()
{
    m_instance = new T();
}

template <class T>
T* singleton<T>::GetInstance()
{
    pthread_once(&m_once,Init);
    return m_instance;
}

template <class T>
pthread_once_t singleton<T>::m_once = PTHREAD_ONCE_INIT;

template <class T>
T* singleton<T>::m_instance = NULL;

在上面的实现中,在实例化对象时,调用GetInstance()函数时都没有传递参数,这是犹豫不同的对象其初始化时参数个数都不一样。如果要支持不同类型的对象带参数初始化,则需要重载GetInstance函数。然而在c++11中,已经支持了可变参数函数。这里给出一个简单的例子:

#ifndef _SINGLETON_H_
#define _SINGLETON_H_

template <class T>
class singleton
{
    protected:
        singleton(){};

    private:
        singleton(const singleton&){};
        singleton& operator=(const singleton&){};
        static T* m_instance;

    public:
        template <typename... Args>
        static T* GetInstance(Args&&... args)
        {
            if(m_instance == NULL)
                m_instance = new T(std::forward<Args>(args)...);
            return m_instance;
        }


    static void DestroyInstance()
    {
        if(m_instance )
            delete m_instance;
        m_instance = NULL;
    }
};


template <class T>
T* singleton<T>::m_instance = NULL;

#endif

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值