标签:
LockableObject类
#include<Windows.h>
//除了构造函数,其它成员函数都声明为虚函数
class LockableObject{
public:
LockableObject(){}
virtual ~LockableObject(){}
virtual void Lock() = 0;
virtual void Unlock() = 0;
private:
CRITICAL_SECTION m_CritSect;
};
//从lockableObject派生而来的CriticalSection
class CriticalSectionV2 :public LockableObject
{
public:
CriticalSectionV2();
virtual ~CriticalSectionV2();
virtual void Lock();
virtual void Unlock();
private:
CRITICAL_SECTION m_CritSect;
};
CriticalSectionV2::CriticalSectionV2()
{
InitializeCriticalSection(&m_CritSect);
}
CriticalSectionV2::~CriticalSectionV2()
{
DeleteCriticalSection(&m_CritSect);
}
void CriticalSectionV2::Lock()
{
EnterCriticalSection(&m_CritSect);
}
void CriticalSectionV2::Unlock()
{
LeaveCriticalSection(&m_CritSect);
}
//一个极安全又简单无比的Lock
class LockV2
{
public:
LockV2(LockableObject* pLockable);
~LockV2();
private:
LockableObject* m_pLockable;
};
LockV2::LockV2(LockableObject* pLockable)
{
m_pLockable = pLockable;
m_pLockable->Lock();
}
LockV2::~LockV2()
{
m_pLockable->Unlock();
}
//criticalSectionV2和Lockv2,彼此间互有协定。
//以安全又简单无比的lock重写string类
class StringV2
{
public:
StringV2();
virtual ~StringV2();
virtual void Set(char* str);
int GetLength();
private:
CriticalSectionV2 m_Lockable;
char* m_pData;
};
StringV2::StringV2()
{
m_pData = NULL;
}
StringV2::~StringV2()
{
delete [] m_pData;
}
void StringV2::Set(char *str)
{
LockV2 localLock(&m_Lockable);
delete[] m_pData;
m_pData = NULL;
m_pData = new char[::strlen(str) + 1];
::strcpy(m_pData, str);
}
int StringV2::GetLength()
{
LockV2 localLock(&m_Lockable);
if (m_pData == NULL)
return 0;
return ::strlen(m_pData);
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/wangfengfan1/article/details/47105185