linux 读者写着问题
来源:互联网 发布:计算机代码编程 编辑:程序博客网 时间:2024/06/04 17:40
读者优先
1. 读者
1) 写者写时,不可读
2) 有别的读者正在读,可读
2. 写者
1) 有读者正在读,不可写
2) 有写者正在写,不可写
3) 无读者正在读,无写者正在写,可写
#include <iostream>#include <stdio.h>#include <stdlib.h>#include <pthread.h>#include <unistd.h>#include <semaphore.h>#define READER 5#define WRITER 3 using namespace std;int readcont=0;sem_t cont;sem_t write1;pthread_t rid[READER];pthread_t wid[WRITER];void *Reader(int*arg){ int read=*(arg); while(true){ sem_wait(&cont); readcont++; if(readcont==1){ sem_wait(&write1); //主要理解这点 } sem_post(&cont); cout<<"reader"<<read<<"is reading"<<endl; sleep(1); sem_wait(&cont); readcont--; cout<<"reader"<<read<<" is over"<<endl; if(readcont==0){ sem_post(&write1); } sem_post(&cont); }}void *Writer(int*arg){ int writer=*(arg); while(true){ sem_wait(&write1); cout<<"writer"<<writer<<" is writing"<<endl; sleep(1); cout<<"writer"<<writer<<" is over"<<endl; sem_post(&write1); }}int main(){ int a[5]={1,2,3,4,5}; sem_init(&cont,0,1); sem_init(&write1,0,1); for(int i=0; i<READER; i++){ pthread_create(&rid[i],NULL,Reader,&a[i]); } for(int i=0; i<WRITER; i++){ pthread_create(&wid[i],NULL,Writer,&a[i]); } for(int i=0; i<READER; i++){ pthread_join(rid[i],NULL); } for(int i=0; i<WRITER; i++){ pthread_join(wid[i],NULL); } return 0;}
阅读全文
0 0
- linux 读者写着问题
- linux 读者写着问题 c++
- linux读者写者问题
- linux 读者写者问题 读者优先c++
- 第二类读者写着问题
- Windows多线程 经典读者写着问题
- 读者写者问题
- 读者写者问题
- 读者-写者问题
- 读者写者问题
- 读者写者问题
- 读者-写者问题
- 读者-写者问题
- 读者-写者问题
- 读者写者问题
- 读者-写者问题
- 读者-写者问题
- 读者写者问题
- JUnit4 基础
- spring boot整合quartz实现多个定时任务
- 怎么解决python "Non-ASCII character"错误?
- 正确引入aar项目之后,发生资源冲突的现象
- Vue之slot分发内容
- linux 读者写着问题
- Djongo页面文件上传,调用静态文件资源
- java中登录验证码的使用
- SQL server 2000服务MSSQLSERVER无法启动解决办法
- Git在mac中和远程仓库建立连接
- 机器学习_隐马尔可夫模型HMM
- 回首2017,盘点最优秀的10大Linux发行版
- git创建分支
- 根据屏幕分辨率操作