您的位置:首页 > 其它

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

2016-09-16 21:18 411 查看
#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;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: