加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
first_reader_writer.cpp 919 Bytes
一键复制 编辑 原始数据 按行查看 历史
chq666666 提交于 2022-01-11 12:08 . first
#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();
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化