-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathblocking_queue.h
More file actions
63 lines (58 loc) · 1.65 KB
/
blocking_queue.h
File metadata and controls
63 lines (58 loc) · 1.65 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
#include <iostream>
#include <deque>
#include <mutex>
#include <condition_variable>
template <class T, class Container = std::deque<T>>
class BlockingQueue {
public:
explicit BlockingQueue(const size_t& capacity) {
capacity_of_queue = capacity;
number_of_items = 0;
shutdown = false;
}
void Put(T&& element) {
std::unique_lock<std::mutex> mutex(mutex0);
while (!shutdown && number_of_items == capacity_of_queue) {
full_queue.wait(mutex);
}
if (shutdown) {
throw std::runtime_error("");
} else {
queue.push_back(std::move(element));
new_item_in_queue.notify_all();
++number_of_items;
}
return;
}
bool Get(T& result) {
std::unique_lock<std::mutex> mutex(mutex0);
while (!shutdown && number_of_items == 0) {
new_item_in_queue.wait(mutex);
}
if (!shutdown || number_of_items > 0) {
result = std::move(queue.front());
queue.pop_front();
if (number_of_items == capacity_of_queue) {
full_queue.notify_all();
}
--number_of_items;
return true;
} else {
return false;
}
}
void Shutdown() {
std::unique_lock<std::mutex> mutex(mutex0);
shutdown = true;
full_queue.notify_all();
new_item_in_queue.notify_all();
}
private:
size_t capacity_of_queue;
size_t number_of_items;
bool shutdown;
Container queue;
std::mutex mutex0;
std::condition_variable new_item_in_queue;
std::condition_variable full_queue;
};