单体模式算是最简单的设计模式,不考虑多线程,我们可能会写出这样的代码:
class Singleton
{
public:
static Singleton* getInstance();
protected:
Singleton(){};
~Singleton(){};
private:
static Singleton* Instance;
};
Singleton* Singleton::Instance = 0;
Singleton* Singleton::getInstance()
{
if(Instance == 0) //position 1
Instance = new Singleton();
return Instance;
}
这段代码在单线程的情况下工作的足够好,但是在多线程下则是不安全的。比如同时有两个线程执行到position 1这个位置,那程序就悲剧了。
网上有多个版本的多线程安全的单体模式,而且有些版本的说两次检查类型的也是不安全的,但是个人测试是可以的,代码如下:
#ifndef SINGLE_H
#define SINGLE_H
#include <Windows.h>
#include <iostream>
using namespace std;
CRITICAL_SECTION m_Section;
class Locker
{
public:
Locker()
{
InitializeCriticalSection(&m_Section);
}
~Locker(){}
void Lock()
{
EnterCriticalSection(&m_Section);
}
void UnLock()
{
LeaveCriticalSection(&m_Section);
}
};
Locker Lock;
class Singleton
{
public:
static Singleton* getInstance();
protected:
Singleton();
~Singleton(){};
private:
static Singleton* Instance;
static HANDLE m_hMutex;
};
Singleton* Singleton::Instance = 0;
HANDLE Singleton::m_hMutex = 0;
Singleton::Singleton()
{
m_hMutex = CreateMutexEx(NULL,NULL,0,0);
cout<<"Constructor function."<<endl;
}
Singleton* Singleton::getInstance()
{
if(Instance == 0)
{
Lock.Lock();
if(Instance == 0)
{
Instance = new Singleton();
}
Lock.UnLock();
}
return Instance;
}
#endif
凑合能用。
还有很多关于多线程安全的Singleton,以后有时间再慢慢细看。
原文链接: https://www.cnblogs.com/henzhi/archive/2012/09/19/13493389.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/63217
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!