项目中用到了此类,实现了多个线程读、单个线程写的功能,基于Windows平台。
思想:两个相关的锁,一个用于读,一个用于写。可以多个同时读,但只能一个写。比传统的互斥锁,提高了一定的并发性。
#ifndef READER_WRITER_LOCK_H_
#define READER_WRITER_LOCK_H_
/*************************************************************
/* Multi-reader Single-writer class
/* author: http://vcsky.net 2011/05/18
**************************************************************/
#include "windows.h"
class CReaderWriterLock
{
public:
CReaderWriterLock()
{
m_Readers = 0;
InitializeCriticalSection(&m_Writer);
InitializeCriticalSection(&m_ReaderCount);
m_ClearReadersEvent = CreateEvent(NULL,TRUE,TRUE,NULL);
}
~CReaderWriterLock()
{
WaitForSingleObject(m_ClearReadersEvent,INFINITE);
CloseHandle(m_ClearReadersEvent);
DeleteCriticalSection(&m_Writer);
DeleteCriticalSection(&m_ReaderCount);
}
/*Read, reset events */
void EnterReader(void)
{
EnterCriticalSection(&m_Writer);
EnterCriticalSection(&m_ReaderCount);
if (++m_Readers == 1)
{
::ResetEvent(m_ClearReadersEvent);
}
LeaveCriticalSection(&m_ReaderCount);
LeaveCriticalSection(&m_Writer);
}
/*leave read, triggered events */
void LeaveReader(void)
{