读者作家锁

时间:2014-03-15 03:43:12

标签: c++ multithreading locking

我正在执行这里提到的多个读/写锁 MultiplereadersWriterLock

这里的EnterReader代码是

void EnterReader(void)
    {
        EnterCriticalSection(&m_csWrite);
        EnterCriticalSection(&m_csReaderCount);
        if (++m_cReaders == 1)
            ResetEvent(m_hevReadersCleared);
        LeaveCriticalSection(&m_csReaderCount);
        LeaveCriticalSection(&m_csWrite);
    }

根据我对这个锁的理解,我们解决了我们可以通过多个线程读取共享资源的问题。这意味着多个线程可以调用EnterReader函数而不会阻塞它们可以继续读取。

示例

Thread T1 calls EnterReader()
It acquires m_csWrite
It acquires m_csReaderCount
Interrupted by CPU and thread T2 starts

    Thread T2 calls EnterReader()
    Since m_csWrite already acquired by T1 so how thread T2 can perform read. 
T2 cannot proceed further since m_csWrite is already acquired that means T2 reader thread is blocked and waiting for T1 to get finish.

我很困惑这个实现如何解决多个读者访问共享资源的问题。

1 个答案:

答案 0 :(得分:0)

EnterReader只是快速锁定以增加读者的数量。注意它在返回之前释放锁。在阅读时,m_csWrite不会像EnterReaderLeaveReader之间那样在EnterWriterLeaveWriter来电之间保持锁定。

用法示例:

lock->EnterReader();
/*Do the reading*/ //No locks here. m_csReaderCount is blocking writes.
lock->LeaveReader();