您的位置:首页 > 其它

Singleton单例模式

2015-06-22 21:57 246 查看
#include <iostream>
#include <windows.h>
#include <mutex>
using namespace std;
std::mutex _sMutex;
template<typename Type>
class Singleton
{
public:
static Type* GetSigleton()
{
if (singlen == NULL)
{
unique_lock<std::mutex> lock(_sMutex);//C++11的加锁语法。
//unique_lock 的生命周期结束之后,它所管理的锁对象会被解锁,
if (singlen == NULL)
{
#ifndef _WIN32
#define _WIN32
#endif
Type* tmp = new Type();
MemoryBarrier();
//栅栏让此前的代码执行完才执行后面的,防止CPU优化导致多线程代码执行混乱。
singlen = tmp;
//如果直接signlen = new Type();//这里审请空间,调用构造,
//赋值三步操作可能混乱。
}
}
return singlen;
}
private:
static Type *singlen;//防止优化,让每次singlen的取值都是在内存中。
};
template<typename Type>
Type * Singleton<Type>::singlen = NULL;

class Test
{
public:
void Printf()
{
cout << "This is Test :: Printf()" << endl;
}
};
int main()
{
Singleton<Test> ::GetSigleton()->Printf();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: