CritSection.h 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #ifndef __CRITSECTION_20160221__
  2. #define __CRITSECTION_20160221__
  3. // ÁÙ½çÖµ;
  4. class ThreadSection
  5. {
  6. public:
  7. ThreadSection(){
  8. HRESULT hr = Init();
  9. (hr);
  10. }
  11. ~ThreadSection(){
  12. DeleteCriticalSection(&_CriticalSection);
  13. }
  14. bool Lock()
  15. {
  16. bool result = false;
  17. __try
  18. {
  19. EnterCriticalSection(&_CriticalSection);
  20. result = true;
  21. }
  22. __except (STATUS_NO_MEMORY == GetExceptionCode())
  23. {
  24. }
  25. return result;
  26. }
  27. bool Unlock()
  28. {
  29. bool result = false;
  30. __try
  31. {
  32. LeaveCriticalSection(&_CriticalSection);
  33. result = true;
  34. }
  35. __except (STATUS_NO_MEMORY == GetExceptionCode())
  36. {
  37. }
  38. return result;
  39. }
  40. private:
  41. HRESULT Init() throw()
  42. {
  43. HRESULT hRes = E_FAIL;
  44. __try
  45. {
  46. InitializeCriticalSection(&_CriticalSection);
  47. hRes = S_OK;
  48. }
  49. __except (STATUS_NO_MEMORY == GetExceptionCode())
  50. {
  51. hRes = E_OUTOFMEMORY;
  52. }
  53. return hRes;
  54. }
  55. ThreadSection(const ThreadSection & tSection);
  56. ThreadSection &operator=(const ThreadSection & tSection);
  57. CRITICAL_SECTION _CriticalSection;
  58. };
  59. class AutoThreadSection
  60. {
  61. public:
  62. AutoThreadSection(IN ThreadSection* pSection){
  63. _pSection = pSection;
  64. _pSection->Lock();
  65. }
  66. ~AutoThreadSection(){
  67. _pSection->Unlock();
  68. }
  69. private:
  70. AutoThreadSection(const AutoThreadSection & tSection);
  71. AutoThreadSection &operator=(const AutoThreadSection & tSection);
  72. ThreadSection * _pSection;
  73. };
  74. #endif //__CRITSECTION_20160221__