c++11 实现读者优先

#include<iostream>
#include<mutex>
#include<condition_variable>
#include<thread>
#include<string>
using namespace std;
class semaphere{
	public: 
	semaphere(int n):m_count(n){}
	semaphere(const semaphere& s)=delete;
	semaphere & operator=(const semaphere& s)=delete;
	void Wait(){
		unique_lock<mutex> lc(m_mtx);
		m_cv.wait(lc,[&]{return m_count>0;});
		m_count--;
	}
	void Signal(){
		{
				unique_lock<mutex> lc(m_mtx);
				m_count++;
		}
		m_cv.notify_one();
	}
	private:
		mutex m_mtx;
		condition_variable m_cv;
		int m_count;
}; 
//读者优先
semaphere  mtx(1),rw(1);
int reader_count=0;
string read_context="hello world";
int w_times=0;
void reader_0(){
	mtx.Wait();
	reader_count++;
	if(reader_count==1) rw.Wait();
	mtx.Signal();
//	cout<<"reding time"<<endl;
	cout<< read_context<<endl;
	this_thread::sleep_for(chrono::milliseconds(1000));
	mtx.Wait();
	reader_count--;
	if(reader_count==0) rw.Signal();
	mtx.Signal();
};
void write_0(){
	rw.Wait();
//	cout<<"reding time"<<endl;
	this_thread::sleep_for(chrono::milliseconds(1000));
	read_context="hello world"+to_string(++w_times); 
	rw.Signal();
}
// 读写公平   多引入一个信号量用于读者写着竞争 
//semaphere mtx1(1), mtx1_for_read_count(1),rw(1);
//int reader_count_justy=0;
//void  reader_1(){
//	
//} 	 
int main(){
	thread  t_r[5];
	for(auto &t:t_r) t=thread(reader_0);
	thread  t_w(write_0);
	thread  t_r1[5];
	for(auto &t:t_r1) t=thread(reader_0);
	for(auto &t:t_r) t.join();
	for(auto &t:t_r1) t.join();
	t_w.join();
	thread  t_r3[5];
	for(auto &t:t_r3) t=thread(reader_0);
	for(auto &t:t_r3) t.join();
	return 0;
} 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值