先看看其代码:
声明:
/////////////////////////////////////////////////////////////////////////////
// CSingleLock
class CSingleLock
{
// Constructors
public:
CSingleLock(CSyncObject* pObject, BOOL bInitialLock = FALSE);
// Operations
public:
BOOL Lock(DWORD dwTimeOut = INFINITE);
BOOL Unlock();
BOOL Unlock(LONG lCount, LPLONG lPrevCount = NULL);
BOOL IsLocked();
// Implementation
public:
~CSingleLock();
protected:
CSyncObject* m_pObject;
HANDLE m_hObject;
BOOL m_bAcquired;
};
实现:
/////////////////////////////////////////////////////////////////////////////
// CSingleLock
CSingleLock::CSingleLock(CSyncObject* pObject, BOOL bInitialLock)
{
ASSERT(pObject != NULL);
ASSERT(pObject->IsKindOf(RUNTIME_CLASS(CSyncObject)));
m_pObject = pObject;
m_hObject = pObject->m_hObject;
m_bAcquired = FALSE;
if (bInitialLock)
Lock();
}
BOOL CSingleLock::Lock(DWORD dwTimeOut /* = INFINITE */)
{
ASSERT(m_pObject != NULL || m_hObject != NULL);
ASSERT(!m_bAcquired);
m_bAcquired = m_pObject->Lock(dwTimeOut);
return m_bAcquired;
}
BOOL CSingleLock::Unlock()
{
ASSERT(m_pObject != NULL);
if (m_bAcquired)
m_bAcquired = !m_pObject->Unlock();
// successfully unlocking means it isn't acquired
return !m_bAcquired;
}
BOOL CSingleLock::Unlock(LONG lCount, LPLONG lpPrevCount /* = NULL */)
{
ASSERT(m_pObject != NULL);
if (m_bAcquired)
m_bAcquired = !m_pObject->Unlock(lCount, lpPrevCount);
// successfully unlocking means it isn't acquired
return !m_bAcquired;
}
BOOL CSingleLock::IsLocked()
{
return m_bAcquired;
}
CSingleLock::~CSingleLock()
{
Unlock();
}
综上得CSingleLock之使用:
1、
CSingleLock在函数内使用,当函数返回时将释放CSingleLock对象,同时进行解锁
------------------------------------
2、
CSingleLock对象在栈上定义,构造时,Lock;CSingleLock的析构函数会自动调用同步对象的Unlock。
---------------------------------------
3、
CSingleLock就是为了使用方便才定义的,你作为成员变量失去他本来的意义了
-------------------------------------------