生产者消费者问题

这是一个非常经典的多线程题目,题目大意如下:有一个生产者在生产产品,这些产品将提供给若干个消费者去消费,为了使生产者和消费者能并发执行,在两者之间设置一个有多个缓冲区的缓冲池,生产者将它生产的产品放入一个缓冲区中,消费者可以从缓冲区中取走产品进行消费,所有生产者和消费者都是异步方式运行的,但它们必须保持同步,即不允许消费者到一个空的缓冲区中取产品,也不允许生产者向一个已经装满产品且尚未被取走的缓冲区中投放产品。

解决答案:

 1 #include <iostream>
 2 #include <stdlib.h>
 3 #include <pthread.h>
 4 using namespace std;
 5 
 6 #define NUM 10
 7 #define Count 20
 8  
 9 pthread_mutex_t myloackA=PTHREAD_MUTEX_INITIALIZER;
10 pthread_mutex_t myloackB=PTHREAD_MUTEX_INITIALIZER;
11 
12 int  amount=0;
13 void *Producer(void *arg)
14 {
15     for (int i = 0; i < Count;)
16     {
17         pthread_mutex_lock(&myloackA);
18         if (amount>=10)
19         {
20             cout<<"已满"<<endl;
21         }
22         else
23         {
24             amount++;
25             cout<<"余下:"<<amount<<endl;
26              ++i;
27         }
28         pthread_mutex_unlock(&myloackB);
29     }
30 
31 }
32 
33 void *Consumer(void *arg)
34 {
35 
36     for (int i = 0; i < Count; )
37     {
38         pthread_mutex_lock(&myloackB);
39         if (amount<=0)
40         {
41             cout<<"为空"<<endl;
42         }
43         else
44         {
45             amount--;
46             cout<<"余下:"<<amount<<endl;
47             ++i;
48         }
49         pthread_mutex_unlock(&myloackA);
50     }
51 }
52 
53 int  main(int argc, char const *argv[])
54 {
55 
56     pthread_t id[2];
57 
58     int err=pthread_create(&id[0],NULL,Producer,NULL);
59     if (err!=0)
60     {
61         cout<<"create err:"<<endl;
62         exit(-1);
63     }
64     err=pthread_create(&id[1],NULL,Consumer,NULL);
65     if (err!=0)
66     {
67         cout<<"create err:"<<endl;
68         exit(-1);
69     }
70     int ret=pthread_join(id[0],NULL);
71     if (ret!=0)
72     {
73         cout<<"join err:"<<endl;
74         exit(-1);
75     }
76     ret=pthread_join(id[1],NULL);
77     if (ret!=0)
78     {
79         cout<<"join err:"<<endl;
80         exit(-1);
81     }
82     return 0;
83 }
原文地址:https://www.cnblogs.com/lanye/p/3371182.html