-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathProducer_Consumer.cpp
More file actions
99 lines (77 loc) · 1.88 KB
/
Copy pathProducer_Consumer.cpp
File metadata and controls
99 lines (77 loc) · 1.88 KB
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include <vector>
#include <mutex>
#include <thread>
#include <condition_variable>
#include <iostream>
using namespace std;
//环形缓冲区的实现,生产者与消费者的模式
template <typename T>
class BoundBuffer
{
private:
vector<T> m_buffer;
mutex m_mutex;
int capacity;
int curSize;
int start;
int end;
condition_variable not_full;
condition_variable not_empty;
public:
BoundBuffer(int c) : capacity(c),curSize(0),start(0),end(0) {
m_buffer.resize(c);
}
void Produce(T x)
{
unique_lock<mutex> lock(m_mutex);
not_full.wait(lock,[=]{return curSize < capacity;});
m_buffer[end] = x;
end = (end + 1) % capacity;
++curSize;
cout << "Produce successfully: " << x << " in thread: " << this_thread::get_id() << endl;
lock.unlock();
not_empty.notify_one();
}
T Consume()
{
unique_lock<mutex> lock(m_mutex);
not_empty.wait(lock,[=]{return curSize > 0;});
T v = m_buffer[start];
start = (start + 1) % capacity;
--curSize;
cout << "Consume successfully: " << v << " in thread: " << this_thread::get_id() << endl;
lock.unlock();
not_full.notify_one();
return v;
}
};
BoundBuffer<int> m_buffer(10);
void Producer()
{
for(int i = 0;i < 100;i++)
{
m_buffer.Produce(i);
}
m_buffer.Produce(-1);
}
void Consumer()
{
thread::id thread_id = this_thread::get_id();
int n = 0;
do{
n = m_buffer.Consume();
}while(n != -1);
m_buffer.Produce(-1);
}
int main()
{
vector<thread> m_threads;
m_threads.push_back(thread(Producer));
m_threads.push_back(thread(Consumer));
m_threads.push_back(thread(Consumer));
m_threads.push_back(thread(Consumer));
for(auto& it : m_threads)
it.join();
system("pause");
return 0;
}