#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;
}