CritSection.h 1.5 KB

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