C++ 读写锁之写优先

VS2005之后可以直接使用SRWLOCK
linux下使用pthread_rwlock_t

本程序基于C++ 11实现读写锁,并且写优先。为什么需要写优先?防止大量读导致写一直不可用。但是当写优先的情况下,如果存在大量写的情况下,也会导致读一直不可用。

适用场景:大量读少量写

基本思想:

  1. 读:是否有写准备,如果有写准备或写计数大于0则执行则等待,否则读计数+1
  2. 写:标记写准备,然后检查是否存在读,如果存在读则等待,否则写计数+1

写优先的读写锁

#pragma once
#include 
#include 
#include 
/*
c++11,读写锁,写优先
*/

class CRWMtx
{
public:
	CRWMtx()
	{
		m_WrCount = 0;
		m_RdCount = 0;
		m_bWriteFinished = true;
	}
	~CRWMtx(){}

	void RLock()
	{
		std::unique_lock<std::mutex> lk(m_mtx);
		//需要双重检查,可能存在m_bWriteFinished为true但是m_WrCount>0
		m_rd_cv.wait(lk, [this]{return m_bWriteFinished && (m_WrCount == 0); });
		++m_RdCount;
	}

	void RUnLock()
	{
		std::unique_lock<std::mutex> lk(m_mtx);
		--m_RdCount;
		m_rd_cv.notify_all();
	}


	void WLock()
	{
		std::unique_lock<std::mutex> lk(m_mtx);
		m_bWriteFinished = false;
		m_rd_cv.wait(lk, [this]{return (m_RdCount <= 0 && m_WrCount == 0); });
		++m_WrCount;
	}

	void WUnLock()
	{
		std::unique_lock<std::mutex> lk(m_mtx);
		if (--m_WrCount == 0)
		{
			m_bWriteFinished = true;
		}
		m_rd_cv.notify_all();
	}
private:
	std::atomic_bool m_bWriteFinished;//写结束
	std::atomic<unsigned long long> m_WrCount;//当前写数量
	std::atomic<unsigned long long> m_RdCount;//当前读数量
	std::mutex m_mtx;
	std::condition_variable m_rd_cv;
};

class CReadLock
{
public:
	CReadLock(CRWMtx &rwMtx) :m_rwMtx(rwMtx){m_rwMtx.RLock();}
	~CReadLock(){m_rwMtx.RUnLock();}
private:
	CRWMtx &m_rwMtx;
};

class CWiteLock
{
public:
	CWiteLock(CRWMtx &rwMtx) :m_rwMtx(rwMtx){ m_rwMtx.WLock(); }
	~CWiteLock(){ m_rwMtx.WUnLock(); }
private:
	CRWMtx &m_rwMtx;
};


测试结果:
C++ 读写锁之写优先_第1张图片

你可能感兴趣的:(C++,随笔,c++,算法,开发语言,读写锁,rwlock)