项目中用到了此类,实现了多个线程读、单个线程写的功能,基于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)
    {
        EnterCriticalSection(&m_ReaderCount);
        if (--m_Readers == 0)
        {
            ::SetEvent(m_ClearReadersEvent);
        }
        LeaveCriticalSection(&m_ReaderCount);
    }

    /*Only after reading, to be able to write*/
    void EnterWriter(void)
    {
        EnterCriticalSection(&m_Writer);
        WaitForSingleObject(m_ClearReadersEvent,INFINITE);
    }

    void LeaveWriter(void)
    {
        LeaveCriticalSection(&m_Writer);
    }

private:
    CRITICAL_SECTION m_Writer;
    CRITICAL_SECTION m_ReaderCount;
    int m_Readers;
    HANDLE m_ClearReadersEvent;
};

#endif