read/write lock implementation using mutex only?

后端 未结 2 1853
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-03 15:49

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

2条回答
  •  日久生厌
    2021-02-03 16:25

    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

提交回复
热议问题