Win32 实现读写锁

Win32中没有为Xp提供读写锁机制(只为Vista提供了), 由于工作需求,所以自己实现了一个简单的读写锁,具体实现如下:

头文件:rwlocker.h

#ifndef _RWLOCKER_H_ #define _RWLOCKER_H_ #include namespace Locker { class RWLocker { private: unsigned long rcount; //readers CRITICAL_SECTION cs; HANDLE mutex; public: RWLocker() ; ~RWLocker(); void rlock(); void runlock(); void wlock(); void wunlock(); }; } #endif

cpp文件:rwlocker.cpp

#include "rwlocker.h" namespace Locker { RWLocker::RWLocker() { rcount = 0; InitializeCriticalSection(&cs); mutex = CreateMutex(NULL, FALSE, NULL); } RWLocker::~RWLocker() { rcount = 0; ReleaseMutex(mutex); DeleteCriticalSection(&cs); } void RWLocker::rlock() { DWORD dwWaitResult; dwWaitResult = WaitForSingleObject(mutex, INFINITE); switch (dwWaitResult) { // The thread got ownership of the mutex case WAIT_OBJECT_0: __try { if (++rcount == 1) EnterCriticalSection(&cs); } __finally { // Release ownership of the mutex object ReleaseMutex(mutex); } break; // The thread got ownership of an abandoned mutex case WAIT_ABANDONED: break ; } } void RWLocker::runlock() { DWORD dwWaitResult; dwWaitResult = WaitForSingleObject(mutex, INFINITE); switch (dwWaitResult) { // The thread got ownership of the mutex case WAIT_OBJECT_0: __try { if (--rcount == 0) LeaveCriticalSection(&cs); } __finally { // Release ownership of the mutex object ReleaseMutex(mutex); } break; // The thread got ownership of an abandoned mutex case WAIT_ABANDONED: break ; } } void RWLocker::wlock() { EnterCriticalSection(&cs); } void RWLocker::wunlock() { LeaveCriticalSection(&cs); } }

你可能感兴趣的:(Win32)