单例模式的两种线程安全并且效率的写法

#include<iostream>
#include<assert.h>
#include<mutex>
#include<Windows.h>

using namespace std;

mutex mtx;
//懒汉模式
template<class T>
class singleton
{
public:
    static singleton* GetSingleton()
    {
        //双重判断是为了效率,避免多次加锁;
        if (single == NULL)
        {
            std::lock_guard<mutex> lck(mtx);//在离开作用域后自动释放锁
            //mtx.lock();//为了避免在加锁和解锁直接出现异常比如说new,不采用这种方式而采用RAII
            if (single == NULL)
                //这个判断实际只会执行一两次
            {
                //single = new singleton;
                //上面的语句偶尔会在编译器的优化下出现问题;
                singleton* tmp = new singleton;
                MemoryBarrier();//内存栅栏
                single = tmp;
            }
            //mtx.unlock();
        }
        return single;
    }
private:
    singleton()
        :_data(new T)
    {}
    singleton(const singleton&);
    singleton operator=(const singleton&);

    static singleton* single;
private:
    T _data
};

template<class T>
singleton::singleton* single = NULL;
#include<iostream>
#include<assert.h>
#include<mutex>
#include<Windows.h>

using namespace std;
//饿汉模式
singleton<T>::GC gc;

template<class T>
class singleton
{
public:
    //singleton* GetSingleton()
    //{
    //  return &single;
    //}

    //或者这样的实现,外面的staic指针就没必要了
    static singleton GetSingleton()
    {
        static singleton single;//静态变量初始化在main函数之前,不存在线程安全
        return &single;
    }

    static void DelSingleton()//其实大多数情况下不需要销毁单例对象,除非单例对象里有一些数据库链接,文件描述符等;
    {
        delete single;
        single = NULL;
    }

    //在全局定义一个GC类对象;用这样的方式保证程序结束后释放单例对象
    class GC
    {
        ~GC()
        {
            DelSingleton();
        }
    };

private:
    singleton()
        :_data(new T)
    {}
    singleton(const singleton&);
    singleton operator=(const singleton&);

    static singleton* single;
private:
    T _data
};

template<class T>
singleton::singleton* single = new singleton;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值