讀寫鎖(Read-Write Lock)的一種實現

項目中用到了此類,實現了多個線程讀、單個線程寫的功能,基於Windows平臺。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"ide

class CReaderWriterLock
{
public:
    CReaderWriterLock()
    {
        m_Readers = 0;
        InitializeCriticalSection(&m_Writer);
        InitializeCriticalSection(&m_ReaderCount);
        m_ClearReadersEvent = CreateEvent(NULL,TRUE,TRUE,NULL);
    }.net

    ~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);
    }get

    /*leave read, triggered events */
    void LeaveReader(void)
    {
        EnterCriticalSection(&m_ReaderCount);
        if (--m_Readers == 0)
        {
            ::SetEvent(m_ClearReadersEvent);
        }
        LeaveCriticalSection(&m_ReaderCount);
    }it

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

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

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

#endif

相關文章
相關標籤/搜索