信号量




 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:Task(int taskID)
10 {
11     this->taskID = taskID;
12 }
13       void doTask()
14       {
15           std::cout << "handle a task, taskID: " << taskID <<
16               ", threadID: " << pthread_self() << std::endl;
17       }
18 private:
19     int taskID;
20 };
21 pthread_mutex_t mymutex;
22 std::list<Task*> tasks;
23 sem_t mysemaphore;
24 void* consumer_thread(void* param)
25 {
26     Task* pTask = NULL;
27     while (true)
28     {
29         if (sem_wait(&mysemaphore) != 0)
30             continue;
31         if (tasks.empty())
32             continue;
33         pthread_mutex_lock(&mymutex);
34         pTask = tasks.front();
35         tasks.pop_front();
36         pthread_mutex_unlock(&mymutex);
37         pTask->doTask();
38         delete pTask;
39     }
40     return NULL;
41 }
42 void* producer_thread(void* param)
43 {
44     int taskID = 0;
45     Task* pTask = NULL;
46     while (true) {
47         pTask = new Task(taskID);
48         pthread_mutex_lock(&mymutex);
49         tasks.push_back(pTask);
50         std::cout << "produce a task, taskID: " << taskID
51             << ", threadID: " << pthread_self() << std::endl;
52         pthread_mutex_unlock(&mymutex);
53         //释放信号量,通知消费者线程
54         sem_post(&mysemaphore);
55         taskID++;
56         //休眠 1 秒
57         sleep(1);
58     }
59     return NULL;
60 }
61 int main()
62 {
63     pthread_mutex_init(&mymutex, NULL);
64     //初始信号量资源计数为 0
65     sem_init(&mysemaphore, 0, 0);
66     //创建 5 个消费者线程
67     pthread_t consumerThreadID[5];
68     for (int i = 0; i < 5; ++i)
69     {
70         pthread_create(&consumerThreadID[i], NULL,
71             consumer_thread, NULL);
72     }
73     //创建一个生产者线程
74     pthread_t producerThreadID;
75     pthread_create(&producerThreadID, NULL,
76         producer_thread, NULL);
77     pthread_join(producerThreadID, NULL);
78     for (int i = 0; i < 5; ++i)
79     {
80         pthread_join(consumerThreadID[i], NULL);
81     }sem_destroy(&mysemaphore);
82     pthread_mutex_destroy(&mymutex);
83     return 0;
84 }

 

posted @ 2022-01-13 10:18  PanDai  阅读(58)  评论(0)    收藏  举报