#include <shared_mutex>
class readWriteLock {
private:
std::shared_mutex readMtx;
std::mutex writeMtx;
int readCnt; // 已加读锁个数
public:
readWriteLock() : readCnt(0) {}
void readLock()
{
readMtx.lock();
if (++readCnt == 1) {
writeMtx.lock(); // 存在线程读操作时,写加锁(只加一次)
}
readMtx.unlock();
}
void readUnlock()
{
readMtx.lock();
if (--readCnt == 0) { // 没有线程读操作时,释放写锁
writeMtx.unlock();
}
readMtx.unlock();
}
void writeLock()
{
writeMtx.lock();
}
void writeUnlock()
{
writeMtx.unlock();
}
};
进阶版
#pragma once
#include <mutex>
#include <condition_variable>
namespace zone
{
class read_write_mutex
{
public:
read_write_mutex() = default;
~read_write_mutex() = default;
read_write_mutex(const read_write_mutex &) = delete;
read_write_mutex & operator=(const read_write_mutex &) = delete;
read_write_mutex(const read_write_mutex &&) = delete;
read_write_mutex & operator=(const read_write_mutex &&) = delete;
void lock_read() {
std::unique_lock<std::mutex> lock( m_mutex );
m_cond_read.wait(lock, [this]()-> bool {
return m_write_count == 0;
});
++m_read_count;
}
void unlock_read() {
std::unique_lock<std::mutex> lock( m_mutex );
if (--m_read_count == 0 && m_write_count > 0) {
m_cond_write.notify_one();
}
}
void lock_write() {
std::unique_lock<std::mutex> lock( m_mutex );
++m_write_count;
m_cond_write.wait(lock, [this]()-> bool {
return m_read_count == 0 && !m_writing;
});
m_writing = true;
}
void unlock_write() {
std::unique_lock<std::mutex> lock( m_mutex );
if (--m_write_count == 0) {
m_cond_read.notify_all();
} else {
m_cond_write.notify_one();
}
m_writing = false;
}
private:
volatile size_t m_read_count = 0;
volatile size_t m_write_count = 0;
volatile bool m_writing = false;
std::mutex m_mutex;
std::condition_variable m_cond_read;
std::condition_variable m_cond_write;
};