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 <<
17 ", threadID: " << pthread_self() << std::endl;
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
57 << ", threadID: " << pthread_self() << std::endl;
58 pthread_mutex_unlock(&mymutex);
59 //释放信号量,通知消费者线程
60 pthread_cond_signal(&mycv);
61 taskID++;
62 //休眠 1 秒
63 sleep(1);
64 }
65 return NULL;
66 }
67 int main()
68 {
69 pthread_mutex_init(&mymutex, NULL);
70 pthread_cond_init(&mycv, NULL);//创建 5 个消费者线程
71 pthread_t consumerThreadID[5];
72 for (int i = 0; i < 5; ++i)
73 {
74 pthread_create(&consumerThreadID[i], NULL,
75 consumer_thread, NULL);
76 }
77 //创建一个生产者线程
78 pthread_t producerThreadID;
79 pthread_create(&producerThreadID, NULL,
80 producer_thread, NULL);
81 pthread_join(producerThreadID, NULL);
82 for (int i = 0; i < 5; ++i)
83 {
84 pthread_join(consumerThreadID[i], NULL);
85 }
86 pthread_cond_destroy(&mycv);
87 pthread_mutex_destroy(&mymutex);
88 return 0;
89 }