linux 读者写者问题 读者优先c++

#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(void*arg){
    int read =*((int*)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);
        sleep(2);
    }
}
void *Writer(void*arg){
    int writer =*((int*)arg);
    while(true){
       sem_wait(&write1);
       cout<<"writer"<<writer<<" is writing"<<endl;
       sleep(1);
       cout<<"writer"<<writer<<" is over"<<endl;
       sem_post(&write1);
       sleep(1);
    }
}

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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值