单例模式 线程安全

1. 首先定义一个 “锁” 类

Lock.h

#include 
					 
class Lock {
public :
	Lock(void);
	~Lock(void);
	void RequireLock();
	void ReleaseLock();
private :
	CRITICAL_SECTION m_lock;
};


Lock.cpp

#include "Lock.h"

Lock::Lock(void) {
	InitializeCriticalSection(&m_lock);
}

Lock::~Lock(void) {
	DeleteCriticalSection(&m_lock);
}

void Lock::RequireLock() {
	EnterCriticalSection(&m_lock);
}

void Lock::ReleaseLock() {
	LeaveCriticalSection(&m_lock);
}

2. 定义单例类,这里通过“双锁机制”实现

#include 
#include "Lock.h"
using namespace std;


class singleton {
private :
	static singleton* single;
	static Lock* myLock;
	singleton();
	singleton(const singleton&);
	singleton& operator =(const singleton&);
public :
	static singleton* getInstance();
};

singleton* singleton::single = NULL;
Lock* singleton::myLock = new Lock();

singleton* singleton::getInstance() {
	if(single == NULL) {
		myLock -> RequireLock();
		if(single == NULL)						  
			single = new singleton();
		myLock -> ReleaseLock();
	}
	return single;
}


你可能感兴趣的:(单例模式 线程安全)