歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Linux多線程──讀者寫者問題

Linux多線程──讀者寫者問題

日期:2017/3/1 10:17:06   编辑:Linux編程

讀者寫者問題

這也是一個非常經典的多線程題目,題目大意如下:有一個寫者很多讀者,多個讀者可以同時讀文件,但寫者在寫文件時不允許有讀者在讀文件,同樣有讀者讀時寫者也不能寫。

程序:

  1. // reader_writer.cpp
  2. //////////////////////////////////////////////////////////////////////
  3. // 讀者寫者問題
  4. // 有一個寫者很多讀者,多個讀者可以同時讀文件,但寫者在寫文件時不允許有讀者在讀文件,
  5. // 同樣有讀者讀時寫者也不能寫。
  6. //////////////////////////////////////////////////////////////////////
  7. #include <pthread.h>
  8. #include <stdio.h>
  9. #include <unistd.h>
  10. // 定義數據類
  11. class data
  12. {
  13. public:
  14. data(int i, float f):
  15. I(i), F(f)
  16. {}
  17. int I;
  18. float F;
  19. };
  20. // 讀者寫者讀寫的內容
  21. data *p_data = NULL;
  22. pthread_rwlock_t lock;
  23. // 寫者數目
  24. const int WRITER_NUMBER = 2;
  25. void *reader(void *arg);
  26. void *writer(void *arg);
  27. int main(int argc, char **argv)
  28. {
  29. pthread_t reader_tid;
  30. pthread_t writer_tid[WRITER_NUMBER];
  31. pthread_create(&reader_tid, NULL, reader, NULL);
  32. for (int i = 0; i < WRITER_NUMBER; ++i)
  33. {
  34. pthread_create(&writer_tid[i], NULL, writer, (void *)i);
  35. }
  36. sleep(1);
  37. return 0;
  38. }
  39. void *reader(void *arg)
  40. {
  41. int id = (int)arg;
  42. pthread_detach(pthread_self());
  43. while (true)
  44. {
  45. pthread_rwlock_rdlock(&lock);
  46. printf("reader %d is reading the data; ", id);
  47. if (p_data == NULL)
  48. {
  49. printf("the data is NULL\n");
  50. }
  51. else
  52. {
  53. printf("the data is (%d, %f)\n", p_data->I, p_data->F);
  54. }
  55. pthread_rwlock_unlock(&lock);
  56. }
  57. return (void *)0;
  58. }
  59. void *writer(void *arg)
  60. {
  61. pthread_detach(pthread_self());
  62. while (true)
  63. {
  64. pthread_rwlock_wrlock(&lock);
  65. printf("writer is writing the data; ");
  66. if (p_data == NULL)
  67. {
  68. p_data = new data(1, 1.1f);
  69. printf("writer create the data (%d, %f)\n", p_data->I, p_data->F);
  70. }
  71. else
  72. {
  73. delete p_data;
  74. p_data = NULL;
  75. printf("writer free the data\n");
  76. }
  77. pthread_rwlock_unlock(&lock);
  78. }
  79. return (void *)0;
  80. }
Copyright © Linux教程網 All Rights Reserved