歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Linux多線程──主線程和子線程分別循環一定次數

Linux多線程──主線程和子線程分別循環一定次數

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

子線程循環 10 次,接著主線程循環 100 次,接著又回到子線程循環 10 次,接著再回到主線程又循環 100 次,如此循環50次,試寫出代碼。

要注意條件變量的自動復位問題。參看這篇文章:Linux 的多線程編程的高效開發經驗 http://www.linuxidc.com/Linux/2009-04/19615.htm

代碼:

  1. #include <pthread.h>
  2. #include <stdio.h>
  3. // 互斥鎖,條件變量
  4. pthread_mutex_t mutex;
  5. pthread_cond_t cond;
  6. // 循環次數
  7. int main_count = 0;
  8. int subthread_count = 0;
  9. // 線程等待標志
  10. bool main_thread_wait_flag = false;
  11. bool subthread_wait_flag = false;
  12. void main_thread_func();
  13. void *subthread_func(void *arg);
  14. int main(int argc, char **argv)
  15. {
  16. pthread_t tid;
  17. pthread_mutex_init(&mutex, NULL);
  18. pthread_cond_init(&cond, NULL);
  19. pthread_create(&tid, NULL, subthread_func, NULL);
  20. main_thread_func();
  21. pthread_join(tid, NULL);
  22. return 0;
  23. }
  24. void main_thread_func()
  25. {
  26. while (true)
  27. {
  28. pthread_mutex_lock(&mutex);
  29. main_thread_wait_flag = true;
  30. pthread_cond_wait(&cond, &mutex);
  31. main_thread_wait_flag = false;
  32. pthread_mutex_unlock(&mutex);
  33. for (int i = 1; i <= 100; ++i)
  34. {
  35. fprintf(stdout, "main thread: %d\n", i);
  36. }
  37. while (true)
  38. {
  39. pthread_mutex_lock(&mutex);
  40. if (true == subthread_wait_flag)
  41. {
  42. pthread_cond_signal(&cond);
  43. pthread_mutex_unlock(&mutex);
  44. break;
  45. }
  46. pthread_mutex_unlock(&mutex);
  47. }
  48. ++main_count;
  49. if (main_count >= 50)
  50. {
  51. fprintf(stdout, "main thread loop 50 times\n");
  52. break;
  53. }
  54. }
  55. }
  56. void *subthread_func(void *arg)
  57. {
  58. while (true)
  59. {
  60. for (int i = 1; i <= 10; ++i)
  61. {
  62. fprintf(stdout, "subthread: %d\n", i);
  63. }
  64. while (true)
  65. {
  66. pthread_mutex_lock(&mutex);
  67. if (true == main_thread_wait_flag)
  68. {
  69. pthread_cond_signal(&cond);
  70. pthread_mutex_unlock(&mutex);
  71. break;
  72. }
  73. pthread_mutex_unlock(&mutex);
  74. }
  75. pthread_mutex_lock(&mutex);
  76. subthread_wait_flag = true;
  77. pthread_cond_wait(&cond, &mutex);
  78. subthread_wait_flag = false;
  79. pthread_mutex_unlock(&mutex);
  80. ++subthread_count;
  81. if (subthread_count >= 50)
  82. {
  83. fprintf(stdout, "subthread loop 50 times\n");
  84. break;
  85. }
  86. }
  87. return (void *)0;
  88. }
Copyright © Linux教程網 All Rights Reserved