Sunday, October 10, 2010

ReaderWriterLock Implementation with Two Critical Sections

A few days ago I was reading a wiki article about reader-writer locks:


http://en.wikipedia.org/wiki/Readers-writer_lock


it references a Win32 implementation of this pattern at:


http://www.glennslayden.com/code/win32/reader-writer-lock


This implementation uses two critical sections and one auto-reset event.


I’ve realized that the same pattern can be implement without using auto-reset event (only with two critical sections). Here is the sample code:

class ReaderWriterLock
{
public:
ReaderWriterLock()
{
_readers = 0;
InitializeCriticalSection(&_rcs);
InitializeCriticalSection(&_wcs);
}

void BeginRead()
{
EnterCriticalSection(&_rcs);
if (_readers == 0)
{
EnterCriticalSection(&_wcs);
}
_readers++;
LeaveCriticalSection(&_rcs);
}

void EndRead()
{
EnterCriticalSection(&_rcs);
_readers--;
if (_readers == 0)
{
LeaveCriticalSection(&_wcs);
}
LeaveCriticalSection(&_rcs);
}

void BeginWrite()
{
EnterCriticalSection(&_wcs);
}

void EndWrite()
{
LeaveCriticalSection(&_wcs);
}

~ReaderWriterLock()
{
DeleteCriticalSection(&_rcs);
DeleteCriticalSection(&_wcs);
}

private:

int _readers;

CRITICAL_SECTION _rcs;
CRITICAL_SECTION _wcs;
};

No comments: