forked from ZhangGang12/MultiThreadLearning
-
Notifications
You must be signed in to change notification settings - Fork 0
/
producer.cpp
65 lines (53 loc) · 1.38 KB
/
producer.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <iostream>
#include <thread>
#include <mutex>
#include <queue>
#include <condition_variable>
using namespace std;
const int MAX = 20;
mutex mtx;
condition_variable pro,com; //生产者消费者条件变量
queue<int> q;
void consumer() //消费者线程的入口
{
while(true)
{
this_thread::sleep_for(chrono::milliseconds(1000));
unique_lock<mutex> lck(mtx);
com.wait(lck, []{return q.size() != 0; });
cout << "comsumer " << this_thread::get_id() << ":";
q.pop();
cout << q.size() << "\n";
pro.notify_all();
}
}
void producer(int id) //生产者入口
{
while(true)
{
this_thread::sleep_for(chrono::milliseconds(900)); //生产者比消费者快
unique_lock<mutex> lck(mtx);
pro.wait(lck,[]{return q.size() < MAX;}); //如果小于MAX就进入,否则不能进入
cout << "->prodcer " << this_thread::get_id() << ":";
q.push(id);
cout << q.size() << endl;
com.notify_all();
}
}
int main()
{
thread consumers[2],producers[2];
for(int i = 0; i < 2; i++)
{
//创建两个消费者和生产者
producers[i] = thread(producer, i + 1);
consumers[i] = thread(consumer);
}
for(int i = 0; i < 2; ++i)
{
producers[i].join();
consumers[i].join();
}
system("pasue");
return 0;
}