-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathexer06b02-blocking-queue.cpp
More file actions
117 lines (80 loc) · 2.22 KB
/
Copy pathexer06b02-blocking-queue.cpp
File metadata and controls
117 lines (80 loc) · 2.22 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
/*
BLOCKING QUEUE IMPLEMENTATION
Version B02: General blocking queues
Underlying mechanism: Condition variables
*/
#include <iostream>
#include <queue>
#include <string>
#include <chrono>
#include <stdexcept>
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace std;
template <typename T>
class BlockingQueue {
private:
std::condition_variable condEmpty;
std::condition_variable condFull;
std::mutex mut;
int capacity = 0;
std::queue<T> q;
public:
BlockingQueue(int capacity) {
if (capacity <= 0)
throw std::invalid_argument("capacity must be a positive integer");
this->capacity = capacity;
}
void put(const T& value) {
{
std::unique_lock<std::mutex> lk(mut);
while ((int)q.size() >= capacity) {
// Queue is full, must wait for 'take'
condFull.wait(lk);
}
q.push(value);
}
condEmpty.notify_one();
}
T take() {
T result;
{
std::unique_lock<std::mutex> lk(mut);
while (q.empty()) {
// Queue is empty, must wait for 'put'
condEmpty.wait(lk);
}
result = q.front();
q.pop();
}
condFull.notify_one();
return result;
}
};
void producer(BlockingQueue<std::string>* blkQueue) {
auto arr = { "nice", "to", "meet", "you" };
for (auto&& data : arr) {
cout << "Producer: " << data << endl;
blkQueue->put(data);
cout << "Producer: " << data << "\t\t\t[done]" << endl;
}
}
void consumer(BlockingQueue<std::string>* blkQueue) {
std::string data;
std::this_thread::sleep_for(std::chrono::seconds(5));
for (int i = 0; i < 4; ++i) {
data = blkQueue->take();
cout << "\tConsumer: " << data << endl;
if (0 == i)
std::this_thread::sleep_for(std::chrono::seconds(5));
}
}
int main() {
BlockingQueue<std::string> blkQueue(2); // capacity = 2
auto thProducer = std::thread(&producer, &blkQueue);
auto thConsumer = std::thread(&consumer, &blkQueue);
thProducer.join();
thConsumer.join();
return 0;
}