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

原创粉丝点击