#ifndef __PBQLOCK_H__ #define __PBQLOCK_H__ #include class PBQLock { // 构造和析构 public: PBQLock() { ::InitializeCriticalSection( &_cs ); } virtual ~PBQLock() { ::DeleteCriticalSection( &_cs ); } // 方法 public: void Acquire() { ::EnterCriticalSection( &_cs ); } void Release() { ::LeaveCriticalSection( &_cs ); } private: CRITICAL_SECTION _cs; }; class PBQAutoLock { public: PBQAutoLock( PBQLock& lock ) : _lock( lock ) { _lock.Acquire(); } virtual ~PBQAutoLock() { _lock.Release(); } private: PBQLock& _lock; PBQAutoLock& operator=( const PBQAutoLock& ); }; class PBQRWLock { public: class RWLockImpl { friend class PBQRWLock; public: RWLockImpl() : _nInstance(0) { _mutex = CreateMutex(NULL, FALSE, NULL); _evtRead = CreateEvent(NULL, TRUE, TRUE, NULL); _evtWrite = CreateEvent(NULL, TRUE, TRUE, NULL); } virtual ~RWLockImpl() { CloseHandle(_mutex); CloseHandle(_evtRead); CloseHandle(_evtWrite); } private: HANDLE _evtRead; HANDLE _evtWrite; HANDLE _mutex; int _nInstance; protected: void Aqurie(bool bWrite = true) { if (bWrite) { HANDLE handles[2] = { _mutex, _evtWrite }; WaitForMultipleObjects(2, handles, TRUE, INFINITE); ResetEvent(_evtRead); ResetEvent(_evtWrite); _nInstance++; ReleaseMutex(_mutex); } else { HANDLE handles[2] = { _mutex, _evtRead }; WaitForMultipleObjects(2, handles, TRUE, INFINITE); ResetEvent(_evtWrite); _nInstance++; ReleaseMutex(_mutex); } } void Release(void) { WaitForSingleObject(_mutex, INFINITE); _nInstance--; if (_nInstance == 0) { SetEvent(_evtWrite); SetEvent(_evtRead); } ReleaseMutex(_mutex); } }; public: PBQRWLock(RWLockImpl& impl, bool bWrite = true) : _impl(impl) { _impl.Aqurie(bWrite); } virtual ~PBQRWLock() { _impl.Release(); } protected: RWLockImpl& _impl; }; #endif /*__PBQLOCK_H__*/