-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathexer06b01-blocking-queue.cpp
More file actions
111 lines (74 loc) · 2.01 KB
/
Copy pathexer06b01-blocking-queue.cpp
File metadata and controls
111 lines (74 loc) · 2.01 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
/*
BLOCKING QUEUE IMPLEMENTATION
Version B01: General blocking queues
Underlying mechanism: Semaphores
*/
#include <iostream>
#include <queue>
#include <string>
#include <chrono>
#include <stdexcept>
#include <thread>
#include <mutex>
#include <semaphore>
using namespace std;
using cntsemaphore = std::counting_semaphore<>;
template <typename T>
class BlockingQueue {
private:
int capacity;
cntsemaphore semRemain;
cntsemaphore semFill;
std::mutex mut;
std::queue<T> q;
public:
BlockingQueue(int capacity) : capacity(capacity), semRemain(capacity), semFill(0) {
if (this->capacity <= 0)
throw std::invalid_argument("capacity must be a positive integer");
}
void put(const T& value) {
semRemain.acquire();
{
std::unique_lock<std::mutex> lk(mut);
q.push(value);
}
semFill.release();
}
T take() {
T result;
semFill.acquire();
{
std::unique_lock<std::mutex> lk(mut);
result = q.front();
q.pop();
}
semRemain.release();
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;
}