-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathexer06a-blocking-queue.cpp
More file actions
82 lines (54 loc) · 1.41 KB
/
Copy pathexer06a-blocking-queue.cpp
File metadata and controls
82 lines (54 loc) · 1.41 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
/*
BLOCKING QUEUE IMPLEMENTATION
Version A: Synchronous queues
*/
#include <iostream>
#include <string>
#include <chrono>
#include <thread>
#include <semaphore>
using namespace std;
using cntsemaphore = std::counting_semaphore<>;
template <typename T>
class SynchronousQueue {
private:
cntsemaphore semPut = cntsemaphore(1);
cntsemaphore semTake = cntsemaphore(0);
T element;
public:
void put(const T& value) {
semPut.acquire();
element = value;
semTake.release();
}
T take() {
semTake.acquire();
T result = element;
semPut.release();
return result;
}
};
void producer(SynchronousQueue<std::string>* syncQueue) {
auto arr = { "lorem", "ipsum", "dolor" };
for (auto&& data : arr) {
cout << "Producer: " << data << endl;
syncQueue->put(data);
cout << "Producer: " << data << "\t\t\t[done]" << endl;
}
}
void consumer(SynchronousQueue<std::string>* syncQueue) {
std::string data;
std::this_thread::sleep_for(std::chrono::seconds(5));
for (int i = 0; i < 3; ++i) {
data = syncQueue->take();
cout << "\tConsumer: " << data << endl;
}
}
int main() {
SynchronousQueue<std::string> syncQueue;
auto thProducer = std::thread(&producer, &syncQueue);
auto thConsumer = std::thread(&consumer, &syncQueue);
thProducer.join();
thConsumer.join();
return 0;
}