1 #pragma once 2 3 ////////////////////////////////////////////////////////////////////////// 4 // CritSec 5 // Description: Wraps a critical section. 6 ////////////////////////////////////////////////////////////////////////// 7 8 class CritSec 9 { 10 public: 11 CRITICAL_SECTION m_criticalSection; 12 public: CritSec()13 CritSec() 14 { 15 InitializeCriticalSectionEx(&m_criticalSection, 100, 0); 16 } 17 ~CritSec()18 ~CritSec() 19 { 20 DeleteCriticalSection(&m_criticalSection); 21 } 22 _Acquires_lock_(m_criticalSection)23 _Acquires_lock_(m_criticalSection) 24 void Lock() 25 { 26 EnterCriticalSection(&m_criticalSection); 27 } 28 _Releases_lock_(m_criticalSection)29 _Releases_lock_(m_criticalSection) 30 void Unlock() 31 { 32 LeaveCriticalSection(&m_criticalSection); 33 } 34 }; 35 36 37 ////////////////////////////////////////////////////////////////////////// 38 // AutoLock 39 // Description: Provides automatic locking and unlocking of a 40 // of a critical section. 41 // 42 // Note: The AutoLock object must go out of scope before the CritSec. 43 ////////////////////////////////////////////////////////////////////////// 44 45 class AutoLock 46 { 47 private: 48 CritSec *m_pCriticalSection; 49 public: _Acquires_lock_(m_pCriticalSection)50 _Acquires_lock_(m_pCriticalSection) 51 AutoLock(CritSec& crit) 52 { 53 m_pCriticalSection = &crit; 54 m_pCriticalSection->Lock(); 55 } 56 57 _Releases_lock_(m_pCriticalSection) ~AutoLock()58 ~AutoLock() 59 { 60 m_pCriticalSection->Unlock(); 61 } 62 }; 63