两个条件变量实现读写锁,写优先,避免写者饥饿

核心思想:用两个int记录写者数与读者数,用两个条件变量分别作为读者、写者的等待队列。

class wfirtst_rwlock
{
public:
	wfirtst_rwlock()
		:rcount(0), wcount(0),writeflag(true) {}
	void readlock()
	{
		unique_lock ul(mtx);
		cond_r.wait(ul, [this] {return wcount == 0; });
		rcount++;
	}
	void readunlock()
	{
		unique_lock ul(mtx);
		if (--rcount == 0 && wcount>0)
			cond_w.notify_one();
	}
	void writelock()
	{
		unique_lock ul(mtx);
		++wcount;                  //先++,避免写者饥饿
		cond_w.wait(ul, [this] {return rcount == 0 && writeflag; });
		writeflag = false;
	}
	void writeunlock()
	{
		unique_lock ul(mtx);
		if (--wcount == 0)
			cond_r.notify_all();//唤醒所有的读者线程
		else
			cond_w.notify_one();//唤醒一个写者线程
		writeflag = true;
	}
private:
	int rcount;
	int wcount;
	bool writeflag;//是否可写入的标志位
	mutex mtx;
	condition_variable cond_r;//建立读者的等待队列
	condition_variable cond_w;//建立写者的等待队列
};

 

你可能感兴趣的:(c++)