歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Linux多線程──3個子線程輪流運行

Linux多線程──3個子線程輪流運行

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

迅雷筆試題:

編寫一個程序,開啟3個線程,這3個線程的ID分別為A、B、C,每個線程將自己的ID在屏幕上打印10遍,要求輸出結果必須按ABC的順序顯示;如:ABCABC….依次遞推。

程序:

  1. #include <pthread.h>
  2. #include <cstdio>
  3. const int THREAD_NUMBER = 3;
  4. // 子線程的互斥量和條件變量
  5. pthread_mutex_t thread_mutex[THREAD_NUMBER];
  6. pthread_cond_t thread_cond[THREAD_NUMBER];
  7. // 子線程是否正在等待
  8. bool thread_wait_flag[THREAD_NUMBER];
  9. // 標識輪到哪個子線程輸出其ID
  10. pthread_mutex_t mutex;
  11. int thread_turn;
  12. void *thread_func(void *arg);
  13. int main(int argc, char **argv)
  14. {
  15. pthread_t tids[THREAD_NUMBER];
  16. for (int i = 0; i < THREAD_NUMBER; ++i)
  17. {
  18. pthread_mutex_init(&thread_mutex[i], NULL);
  19. pthread_cond_init(&thread_cond[i], NULL);
  20. }
  21. pthread_mutex_init(&mutex, NULL);
  22. thread_turn = 0;
  23. for (int i = 0; i < THREAD_NUMBER; ++i)
  24. thread_wait_flag[i] = false;
  25. for (int i = 0; i < THREAD_NUMBER; ++i)
  26. {
  27. pthread_create(&tids[i], NULL, thread_func, (void *)i);
  28. }
  29. for (int i = 0; i < THREAD_NUMBER; ++i)
  30. {
  31. pthread_join(tids[i], NULL);
  32. }
  33. printf("\n");
  34. return 0;
  35. }
  36. void *thread_func(void *arg)
  37. {
  38. int id = (int)arg;
  39. char ch = 'A' + id;
  40. int count = 0;
  41. while (true)
  42. {
  43. if (id == thread_turn) // 若輪到當前子線程,輸出ID,發送信號
  44. {
  45. printf("%c", ch);
  46. ++count;
  47. if (id == THREAD_NUMBER-1 && count == 10) // 若是第3個子線程,輸出ID後,可直接退出。
  48. break;
  49. pthread_mutex_lock(&mutex);
  50. ++thread_turn;
  51. thread_turn %= THREAD_NUMBER;
  52. pthread_mutex_unlock(&mutex);
  53. while (true)
  54. {
  55. pthread_mutex_lock(&thread_mutex[thread_turn]);
  56. if (true == thread_wait_flag[thread_turn])
  57. {
  58. pthread_cond_signal(&thread_cond[thread_turn]);
  59. pthread_mutex_unlock(&thread_mutex[thread_turn]);
  60. break;
  61. }
  62. pthread_mutex_unlock(&thread_mutex[thread_turn]);
  63. }
  64. if (count == 10) // 若是第1、2個子線程,發出信號後,退出
  65. break;
  66. }
  67. else // 否則,等待
  68. {
  69. pthread_mutex_lock(&thread_mutex[id]);
  70. thread_wait_flag[id] = true;
  71. pthread_cond_wait(&thread_cond[id], &thread_mutex[id]);
  72. thread_wait_flag[id] = false;
  73. pthread_mutex_unlock(&thread_mutex[id]);
  74. }
  75. }
  76. return (void *)0;
  77. }
Copyright © Linux教程網 All Rights Reserved