PBQLock.h 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. #ifndef __PBQLOCK_H__
  2. #define __PBQLOCK_H__
  3. #include <windows.h>
  4. class PBQLock
  5. {
  6. // ¹¹ÔìºÍÎö¹¹
  7. public:
  8. PBQLock()
  9. {
  10. ::InitializeCriticalSection( &_cs );
  11. }
  12. virtual ~PBQLock()
  13. {
  14. ::DeleteCriticalSection( &_cs );
  15. }
  16. // ·½·¨
  17. public:
  18. void Acquire()
  19. {
  20. ::EnterCriticalSection( &_cs );
  21. }
  22. void Release()
  23. {
  24. ::LeaveCriticalSection( &_cs );
  25. }
  26. private:
  27. CRITICAL_SECTION _cs;
  28. };
  29. class PBQAutoLock
  30. {
  31. public:
  32. PBQAutoLock( PBQLock& lock ) : _lock( lock )
  33. {
  34. _lock.Acquire();
  35. }
  36. virtual ~PBQAutoLock()
  37. {
  38. _lock.Release();
  39. }
  40. private:
  41. PBQLock& _lock;
  42. PBQAutoLock& operator=( const PBQAutoLock& );
  43. };
  44. class PBQRWLock
  45. {
  46. public:
  47. class RWLockImpl
  48. {
  49. friend class PBQRWLock;
  50. public:
  51. RWLockImpl()
  52. : _nInstance(0)
  53. {
  54. _mutex = CreateMutex(NULL, FALSE, NULL);
  55. _evtRead = CreateEvent(NULL, TRUE, TRUE, NULL);
  56. _evtWrite = CreateEvent(NULL, TRUE, TRUE, NULL);
  57. }
  58. virtual ~RWLockImpl()
  59. {
  60. CloseHandle(_mutex);
  61. CloseHandle(_evtRead);
  62. CloseHandle(_evtWrite);
  63. }
  64. private:
  65. HANDLE _evtRead;
  66. HANDLE _evtWrite;
  67. HANDLE _mutex;
  68. int _nInstance;
  69. protected:
  70. void Aqurie(bool bWrite = true)
  71. {
  72. if (bWrite)
  73. {
  74. HANDLE handles[2] = { _mutex, _evtWrite };
  75. WaitForMultipleObjects(2, handles, TRUE, INFINITE);
  76. ResetEvent(_evtRead);
  77. ResetEvent(_evtWrite);
  78. _nInstance++;
  79. ReleaseMutex(_mutex);
  80. }
  81. else
  82. {
  83. HANDLE handles[2] = { _mutex, _evtRead };
  84. WaitForMultipleObjects(2, handles, TRUE, INFINITE);
  85. ResetEvent(_evtWrite);
  86. _nInstance++;
  87. ReleaseMutex(_mutex);
  88. }
  89. }
  90. void Release(void)
  91. {
  92. WaitForSingleObject(_mutex, INFINITE);
  93. _nInstance--;
  94. if (_nInstance == 0)
  95. {
  96. SetEvent(_evtWrite);
  97. SetEvent(_evtRead);
  98. }
  99. ReleaseMutex(_mutex);
  100. }
  101. };
  102. public:
  103. PBQRWLock(RWLockImpl& impl, bool bWrite = true)
  104. : _impl(impl)
  105. {
  106. _impl.Aqurie(bWrite);
  107. }
  108. virtual ~PBQRWLock()
  109. {
  110. _impl.Release();
  111. }
  112. protected:
  113. RWLockImpl& _impl;
  114. };
  115. #endif /*__PBQLOCK_H__*/