读写者问题

来源:互联网 发布:手机苏戴斯诵读软件 编辑:程序博客网 时间:2024/06/11 13:26

题目大意如下:有一个写者很多读者,多个读者可以同时读文件,但写者在写文件时不允许有读者在读文件,同样有读者读时写者也不能写。

读者之间因为pthread_mutex_lock(&rd);所以同时只能一个读者。
当有读者的时候,readCount!=0,所以不能写。
当写的时候。readCount==0,同时pthread_mutex_lock(&wr);
所以无法读,因为第一个读者,要检测是不是在写。
每个读,局部变量,控制每个读的结束。
实现了读写同步,读读同步。


#include <pthread.h>#include <signal.h>#define N 5#define M 10pthread_mutex_t rd = PTHREAD_MUTEX_INITIALIZER;pthread_mutex_t wr = PTHREAD_MUTEX_INITIALIZER;pthread_mutex_t priority = PTHREAD_MUTEX_INITIALIZER;int readCount = 0;void* reader(void *arg){int n = M;int id = (int)arg;while (n--) {sleep(rand()%3);pthread_mutex_lock(&priority);pthread_mutex_lock(&rd);readCount++;if ( readCount ==1){pthread_mutex_lock(&wr);}pthread_mutex_unlock(&rd);pthread_mutex_unlock(&priority);printf("reader %d is reading \n",id);sleep(rand()%3);pthread_mutex_lock(&rd);readCount--;if (readCount==0){pthread_mutex_unlock(&wr);}pthread_mutex_unlock(&rd);printf("reader %d is leaving \n",id);}printf("----reader %d has done----\n",(int)arg);}void* writer(void *arg){int n = M;while (n--){sleep (rand()%4);pthread_mutex_lock(&priority);pthread_mutex_lock(&wr);printf("\twriter is writing \n");sleep (rand()%4);pthread_mutex_unlock(&priority);pthread_mutex_unlock(&wr);printf("\twriter is leaving \n");}printf("----writer has done ----\n");}int main (int argc ,const char *asrgv[]){int err;pthread_t tid[N],writer_tid;int i;for (i=0;i<N;i++){err=pthread_create(&tid[i],NULL,reader,(void *)(i+1));if (err !=0) {printf("can;t create process for reader");}}err = pthread_create(&writer_tid,NULL,writer,(void *)NULL);if (err!=0){printf("can;t cretee process for writer\n");}pause ();return 0;}



0 0