windows臨界區鎖的封裝與實現
阿新 • • 發佈:2018-12-10
基於臨界區鎖類的定義(.h):
1 class CMyLock { public: CMyLock(); ~CMyLock(); public: void Lock(); void Unlock();
private: CRITICAL_SECTION m_cs; }; 2 實現方法(.cpp)
CMyLock::CMyLock() { InitializeCriticalSection(&m_cs); }
CMyLock::~CMyLock() { DeleteCriticalSection(&m_cs); }
void CMyLock::Lock() { EnterCriticalSection(&m_cs); }
void CMyLock::Unlock() { LeaveCriticalSection(&m_cs); }
3 自動鎖
class CAutoLock{ public: CAutoLock(CMyLock* pMyLock); ~CAutoLock(); public: CMyLock* m_pMyLock; };
CAutoLock::CAutoLock(CMyLock* pMyLock) { m_pMyLock = pMyLock; if (m_pMyLock) m_pMyLock->Lock();
}
CAutoLock::~CAutoLock() { if (m_pMyLock) m_pMyLock->Unlock(); }