-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathdemo22b-blocking-queue.cpp
More file actions
57 lines (39 loc) · 1.2 KB
/
Copy pathdemo22b-blocking-queue.cpp
File metadata and controls
57 lines (39 loc) · 1.2 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
/*
BLOCKING QUEUES
Version B: A fast producer and a slow consumer
Blocking queues in C++ std threading are not supported by default.
So, I use mylib::BlockingQueue for this demonstration.
*/
#include <iostream>
#include <string>
#include <chrono>
#include <thread>
#include "mylib-blockingqueue.hpp"
using namespace std;
using namespace mylib;
void producer(BlockingQueue<string>* blkQueue) {
blkQueue->put("Alice");
blkQueue->put("likes");
/*
Due to reaching the maximum capacity = 2, when executing blkQueue->put("singing"),
this thread is going to sleep until the queue removes an element.
*/
blkQueue->put("singing");
}
void consumer(BlockingQueue<string>* blkQueue) {
string data;
std::this_thread::sleep_for(std::chrono::seconds(2));
for (int i = 0; i < 3; ++i) {
cout << "\nWaiting for data..." << endl;
data = blkQueue->take();
cout << " " << data << endl;
}
}
int main() {
auto blkQueue = BlockingQueue<string>(2); // blocking queue with capacity = 2
auto thProducer = std::thread(&producer, &blkQueue);
auto thConsumer = std::thread(&consumer, &blkQueue);
thProducer.join();
thConsumer.join();
return 0;
}