1. 程式人生 > >讀者寫者模型(概念&與生產消費者的區別¥讀寫優先順序問題)

讀者寫者模型(概念&與生產消費者的區別¥讀寫優先順序問題)

 
  1 #include<stdio.h>                                                     
  2 #include<pthread.h>
  3                
  4 int book=0;    
  5 pthread_rwlock_t rwlock;
  6                
  7 void *myread(void *arg)
  8 {              
  9     while(1)   
 10     {          
 11     ┊   if(pthread_rwlock_rdlock(&rwlock)!=0)
 12     ┊   {      
 13     ┊   ┊   printf("writer is writing...\n");
 14     ┊   }      
 15     ┊   else   
 16     ┊   {      
 17     ┊   printf("read book done:%d\n",book);
 18     ┊   ┊   sleep(4);
 19     ┊   }      
 20     }          
 21 }              
 22         
 23 void *mywrite(void *arg)
 24 {       
 25     sleep(1);
 26    while(1)
 27     {   
 28     ┊   if(pthread_rwlock_wrlock(&rwlock)!=0)
 29     ┊   { 
 30     ┊   ┊   printf("reader is reading...\n");
 31     ┊   } 
 32     ┊   else
 33     ┊   { 
 34     ┊   book++;
 35     ┊   printf("write book done:%d\n",book);
 36     ┊   sleep(5);
 37     ┊   pthread_rwlock_unlock(&rwlock);
 38     ┊   }
 39     }                                                                 
 40 }    
 41      
 42 int main()
 43 {           
 44     pthread_rwlock_init(&rwlock,NULL);
 45     pthread_t r,w;     
 46     pthread_create(&r,NULL,myread ,NULL);
 47     pthread_create(&w,NULL,mywrite,NULL);
 48             
 49     pthread_join(r,NULL);
 50     pthread_join(w,NULL);
 51     pthread_rwlock_destroy(&rwlock);
 52     return 0;
 53 }                                                                     
執行結果: