代码拉取完成,页面将自动刷新
#include<iostream>
#include<thread>
#include<mutex>
#include<ctime>
#include <semaphore.h>
using namespace std;
using namespace std::this_thread;
using namespace std::chrono;
int readcount=0;
sem_t read_mutex, wrt;
void read(int id){
sem_wait(&read_mutex);
readcount++;
if (readcount == 1) sem_wait(&wrt);
sem_post (&read_mutex);
cout<<"reader"<<id<<"reading is performed"<<endl;
sleep_for(seconds(2));
sem_wait(&read_mutex);
readcount--;
if(readcount == 0) sem_post(&wrt);
sem_post(&read_mutex);
}
void write(int id){
sem_wait(&wrt);
cout<<"writer"<<id<<"writing is performed"<<endl;
sleep_for(seconds(4));
sem_post(&wrt);
}
int main(){
sem_init(&read_mutex,0,1);
sem_init(&wrt,0,1);
thread t1(read, 0);
thread t2(write, 0);
thread t3(read, 1);
thread t4(write, 1);
t1.join(); t2.join();t3.join();t4.join();
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。