I was trying to implement read/write lock using mutex only (just for learning). Just when i thought i have covered all corner cases (as the program worked with variety of combin
class ReadWriteLock {
mutex writeLock;
mutex readLock;
int readCount;
public:
ReadWriteLock() {
readCount = 0;
}
void LockWrite() {
writeLock.lock();
}
void UnlockWrite() {
writeLock.unlock();
}
void LockRead() {
lock_guard lock(readLock);
++readCount;
if (1 == readCount) {
LockWrite();
}
}
void UnlockRead() {
lock_guard lock(readLock);
--readCount;
if (0 == readCount) {
UnlockWrite();
}
}
};
As Alexey pointed out, if the last read thread to UnlockWrite isn't the first read thread to LockWrite, the behavior is undefined. See std::mutex::unlock http://www.cplusplus.com/reference/mutex/mutex/unlock/ Windows ReleaseMutex: http://msdn.microsoft.com/en-us/library/windows/desktop/ms685066(v=vs.85).aspx