Lockable.h: CriticalSection的抽象父类
class LockableObject
{
public:
LockableObject(){}
virtual ~LockableObject(){}
virtual void Lock() = 0;
virtual void Unlock() = 0;
};
CriticalSection.h
#include "LockableObject.h"
#include <windows.h>
class CriticalSection : public LockableObject
{
public:
CriticalSection();
virtual ~CriticalSection();
virtual void Lock();
virtual void Unlock();
private:
CRITICAL_SECTION mCriticalSection;
};
CriticalSection.cpp
#include "CriticalSection.h"
CriticalSection::CriticalSection()
{
InitializeCriticalSection(&mCriticalSection);
}
CriticalSection::~CriticalSection()
{
DeleteCriticalSection(&mCriticalSection);
}
void CriticalSection::Lock()
{
EnterCriticalSection(&mCriticalSection);
}
void CriticalSection::Unlock()
{
LeaveCriticalSection(&mCriticalSection);
}
Lock.h
#include "CriticalSection.h"
class Lock
{
public:
Lock(LockableObject* pLockable);
~Lock();
private:
LockableObject* mLockable;
};
Lock.cpp
#include "Lock.h"
Lock::Lock(LockableObject* pLockable)
{
mLockable = pLockable;
pLockable->Lock();
}
Lock::~Lock()
{
mLockable->Unlock();
}