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 mtx1(1),mtx2(1),mtx3(1),r(1),w(1);
//mtx1 用于控制 reader_count 
//mtx2 用于控制 write_count
//mtx3 用于实现读者并发 
//r  用于控制读者线程 
//w  用于控制写者线程 
//我也不知道这么理解有没有问题   
int reader_count=0;
int write_count=0;
string read_context="hello world";
int w_times=0;
void reader(){
	mtx3.Wait();
	r.Wait();
	mtx1.Wait();
	reader_count++;
	if(reader_count==1) w.Wait();
	mtx1.Signal();
	r.Signal();
	mtx3.Signal();
	this_thread::sleep_for(chrono::milliseconds(1000));
	cout<< read_context<<endl;
	mtx1.Wait();
	reader_count--;
	if(reader_count==0) w.Signal();
	mtx1.Signal();
} 
void write_first(){
	mtx2.Wait();
	write_count++;
	if(write_count==1){
		r.Wait();
	} 
	mtx2.Signal();
	w.Wait();
	this_thread::sleep_for(chrono::milliseconds(1000));
	read_context="hello world"+to_string(++w_times); 
	w.Signal();
	mtx2.Wait();
	write_count--;
	if(write_count==0){
		r.Signal();
	}
	mtx2.Signal();
}	 
int main(){
	thread  t_r[5];
	for(auto &t:t_r) t=thread(reader);
	thread  t_w(write_first);
	thread  t_r1[5];
	for(auto &t:t_r1) t=thread(reader);
	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);
	for(auto &t:t_r3) t.join();
	return 0;
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值