Linux多线程──读者写者问题


读者写者问题

这也是一个非常经典的多线程题目,题目大意如下:有一个写者很多读者,多个读者可以同时读文件,但写者在写文件时不允许有读者在读文件,同样有读者读时写者也不能写。

程序:

  1. // reader_writer.cpp   
  2. //////////////////////////////////////////////////////////////////////   
  3. // 读者写者问题   
  4. // 有一个写者很多读者,多个读者可以同时读文件,但写者在写文件时不允许有读者在读文件,   
  5. // 同样有读者读时写者也不能写。   
  6. //////////////////////////////////////////////////////////////////////   
  7.   
  8. #include <pthread.h>   
  9. #include <stdio.h>   
  10. #include <unistd.h>   
  11.   
  12. // 定义数据类   
  13. class data  
  14. {  
  15. public:  
  16.     data(int i, float f):  
  17.         I(i), F(f)  
  18.     {}  
  19.   
  20.     int I;  
  21.     float F;  
  22. };  
  23.   
  24. // 读者写者读写的内容   
  25. data *p_data = NULL;  
  26.   
  27. pthread_rwlock_t lock;  
  28.   
  29. // 写者数目   
  30. const int WRITER_NUMBER = 2;  
  31.   
  32. void *reader(void *arg);  
  33. void *writer(void *arg);  
  34.   
  35. int main(int argc, char **argv)  
  36. {  
  37.     pthread_t reader_tid;  
  38.     pthread_t writer_tid[WRITER_NUMBER];  
  39.       
  40.     pthread_create(&reader_tid, NULL, reader, NULL);  
  41.     for (int i = 0; i < WRITER_NUMBER; ++i)  
  42.     {  
  43.         pthread_create(&writer_tid[i], NULL, writer, (void *)i);  
  44.     }  
  45.   
  46.     sleep(1);  
  47.       
  48.     return 0;  
  49. }  
  50.   
  51. void *reader(void *arg)  
  52. {  
  53.     int id = (int)arg;  
  54.   
  55.     pthread_detach(pthread_self());  
  56.       
  57.     while (true)  
  58.     {  
  59.         pthread_rwlock_rdlock(&lock);  
  60.         printf("reader %d is reading the data; ", id);  
  61.         if (p_data == NULL)  
  62.         {  
  63.             printf("the data is NULL\n");  
  64.         }  
  65.         else  
  66.         {  
  67.             printf("the data is (%d, %f)\n", p_data->I, p_data->F);  
  68.         }  
  69.         pthread_rwlock_unlock(&lock);  
  70.     }  
  71.     return (void *)0;  
  72. }  
  73.   
  74. void *writer(void *arg)  
  75. {  
  76.     pthread_detach(pthread_self());  
  77.   
  78.     while (true)  
  79.     {  
  80.         pthread_rwlock_wrlock(&lock);  
  81.         printf("writer is writing the data; ");  
  82.         if (p_data == NULL)  
  83.         {  
  84.             p_data = new data(1, 1.1f);  
  85.             printf("writer create the data (%d, %f)\n", p_data->I, p_data->F);  
  86.         }  
  87.         else  
  88.         {  
  89.             delete p_data;  
  90.             p_data = NULL;  
  91.             printf("writer free the data\n");  
  92.         }  
  93.         pthread_rwlock_unlock(&lock);  
  94.     }  
  95.     return (void *)0;  
  96. }  

相关内容