#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;
}
c++11 写者优先
最新推荐文章于 2022-09-06 23:59:02 发布