CritSec.h 1.3 KB

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