CritSection.h 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. #ifndef CRITSECTION_H
  2. #define CRITSECTION_H
  3. #include "sal.h"
  4. /**
  5. * Critical section
  6. * Critical Section object
  7. */
  8. class ThreadSection
  9. {
  10. public:
  11. ThreadSection()
  12. {
  13. HRESULT hr = Init();
  14. (hr);
  15. }
  16. ~ThreadSection()
  17. {
  18. DeleteCriticalSection(&_CriticalSection);
  19. }
  20. /// Enter/Lock a critical section
  21. bool Lock()
  22. {
  23. bool result = false;
  24. __try
  25. {
  26. EnterCriticalSection(&_CriticalSection);
  27. result = true;
  28. }
  29. __except(STATUS_NO_MEMORY == GetExceptionCode())
  30. {
  31. }
  32. return result;
  33. }
  34. /// Leave/Unlock a critical section
  35. bool Unlock()
  36. {
  37. bool result = false;
  38. __try
  39. {
  40. LeaveCriticalSection(&_CriticalSection);
  41. result = true;
  42. }
  43. __except(STATUS_NO_MEMORY == GetExceptionCode())
  44. {
  45. }
  46. return result;
  47. }
  48. private:
  49. /// Initialize critical section
  50. HRESULT Init() throw()
  51. {
  52. HRESULT hRes = E_FAIL;
  53. __try
  54. {
  55. InitializeCriticalSection(&_CriticalSection);
  56. hRes = S_OK;
  57. }
  58. // structured exception may be raised in low memory situations
  59. __except(STATUS_NO_MEMORY == GetExceptionCode())
  60. {
  61. hRes = E_OUTOFMEMORY;
  62. }
  63. return hRes;
  64. }
  65. ThreadSection(const ThreadSection & tSection);
  66. ThreadSection &operator=(const ThreadSection & tSection);
  67. CRITICAL_SECTION _CriticalSection;
  68. };
  69. /**
  70. * AutoThreadSection class
  71. * Critical section auto-lock
  72. */
  73. class AutoThreadSection
  74. {
  75. public:
  76. /// auto section - constructor
  77. AutoThreadSection(__in ThreadSection* pSection)
  78. {
  79. _pSection = pSection;
  80. _pSection->Lock();
  81. }
  82. ~AutoThreadSection()
  83. {
  84. _pSection->Unlock();
  85. }
  86. private:
  87. AutoThreadSection(const AutoThreadSection & tSection);
  88. AutoThreadSection &operator=(const AutoThreadSection & tSection);
  89. ThreadSection * _pSection;
  90. };
  91. #endif //CRITSECTION_H