c++利用互斥锁实现读写锁

很简单就是在读的时候把写的锁锁住就好了

class readwrite_lock  
{  
public:  
    readwrite_lock()  
        : read_cnt(0)  
    {  
    }  
  
    void readLock()  
    {  
        read_mtx.lock();  
        if (++read_cnt == 1)  
            write_mtx.lock();  
  
        read_mtx.unlock();  
    }  
  
    void readUnlock()  
    {  
        read_mtx.lock();  
        if (--read_cnt == 0)  
            write_mtx.unlock();  
  
        read_mtx.unlock();  
    }  
  
    void writeLock()  
    {  
        write_mtx.lock();  
    }  
  
    void writeUnlock()  
    {  
        write_mtx.unlock();  
    }  
  
private:  
    mutex read_mtx;  
    mutex write_mtx;  
    int read_cnt; // 已加读锁个数  
};  

  

转载于:https://www.cnblogs.com/wangshaowei/p/9095438.html

你可能感兴趣的:(c++利用互斥锁实现读写锁)