cv.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. #include <pthread.h>
  2. #include <errno.h>
  3. #include <unistd.h>
  4. #include <list>
  5. #include <semaphore.h>
  6. #include <iostream>
  7. class Task
  8. {
  9. public:
  10. Task(int taskID)
  11. {
  12. this->taskID = taskID;
  13. }
  14. void doTask()
  15. {
  16. std::cout << "handle a task, taskID: " << taskID << ", threadID: " << pthread_self() << std::endl;
  17. }
  18. private:
  19. int taskID;
  20. };
  21. pthread_mutex_t mymutex;
  22. std::list<Task*> tasks;
  23. pthread_cond_t mycv;
  24. void* consumer_thread(void* param)
  25. {
  26. Task* pTask = NULL;
  27. while (true)
  28. {
  29. pthread_mutex_lock(&mymutex);
  30. while (tasks.empty())
  31. {
  32. //如果获得了互斥锁,但是条件不合适的话,pthread_cond_wait会释放锁,不往下执行。
  33. //当发生变化后,条件合适,pthread_cond_wait将直接获得锁。
  34. pthread_cond_wait(&mycv, &mymutex);
  35. }
  36. pTask = tasks.front();
  37. tasks.pop_front();
  38. pthread_mutex_unlock(&mymutex);
  39. if (pTask == NULL)
  40. continue;
  41. pTask->doTask();
  42. delete pTask;
  43. pTask = NULL;
  44. }
  45. return NULL;
  46. }
  47. void* producer_thread(void* param)
  48. {
  49. int taskID = 0;
  50. Task* pTask = NULL;
  51. while (true)
  52. {
  53. pTask = new Task(taskID);
  54. pthread_mutex_lock(&mymutex);
  55. tasks.push_back(pTask);
  56. std::cout << "produce a task, taskID: " << taskID << ", threadID: " << pthread_self() << std::endl;
  57. pthread_mutex_unlock(&mymutex);
  58. //释放条件信号,通知消费者线程
  59. pthread_cond_signal(&mycv);
  60. taskID ++;
  61. //休眠1秒
  62. sleep(1);
  63. }
  64. return NULL;
  65. }
  66. int main()
  67. {
  68. pthread_mutex_init(&mymutex, NULL);
  69. pthread_cond_init(&mycv, NULL);
  70. //创建5个消费者线程
  71. pthread_t consumerThreadID[5];
  72. for (int i = 0; i < 5; ++i)
  73. {
  74. pthread_create(&consumerThreadID[i], NULL, consumer_thread, NULL);
  75. }
  76. //创建一个生产者线程
  77. pthread_t producerThreadID;
  78. pthread_create(&producerThreadID, NULL, producer_thread, NULL);
  79. pthread_join(producerThreadID, NULL);
  80. for (int i = 0; i < 5; ++i)
  81. {
  82. pthread_join(consumerThreadID[i], NULL);
  83. }
  84. pthread_cond_destroy(&mycv);
  85. pthread_mutex_destroy(&mymutex);
  86. return 0;
  87. }