class CLock
{
public:
void Lock()
{EnterCriticalSection(&m_sec);}
void Unlock()
{LeaveCriticalSection(&m_sec);}
CLock ()
{InitializeCriticalSection(&m_sec);}
~ CLock ()
{DeleteCriticalSection(&m_sec);}
private:
CRITICAL_SECTION m_sec;
};
//把加锁和放锁放在构造函数和析构函数里,锁就会随着构造函数和析构函数的调用而加锁和放锁了。
class CAutoLock
{
public:
CAutoLock(CLock
* lpLock) :
m_pLock (lpLock)
{
m_pLock ->Lock();
}
~CAutoLock()
{
m_pLock ->Unlock();
}
private:
CLock * m_pLock;
};
{
CLock m_lock;
CAutoLock(&m_lock);
…
}
Copyright 2011-2020 © MallocFree. All rights reserved.