123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132 |
- #ifndef __PBQLOCK_H__
- #define __PBQLOCK_H__
- #include <windows.h>
- 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__*/
|