-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathBlockingQueue.h
46 lines (43 loc) · 1.09 KB
/
BlockingQueue.h
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
#pragma once
#include <condition_variable>
#include <deque>
#include <mutex>
template <typename T>
class BlockingQueue {
private:
std::mutex d_mutex;
std::condition_variable d_condition;
std::deque<T> d_queue;
public:
template <typename U>
void push(U&& value) {
{
std::scoped_lock lock{this->d_mutex};
d_queue.push_back(std::forward<U>(value));
}
this->d_condition.notify_one();
}
void wait() {
std::unique_lock lock{this->d_mutex};
this->d_condition.wait(lock, [=] { return !this->d_queue.empty(); });
}
T pop() {
std::unique_lock lock{this->d_mutex};
this->d_condition.wait(lock, [=] { return !this->d_queue.empty(); });
T rc(std::move(this->d_queue.front()));
this->d_queue.pop_front();
return rc;
}
void clear() {
std::scoped_lock lock{this->d_mutex};
this->d_queue.clear();
}
std::optional<T> popMaybe() {
std::scoped_lock lock{this->d_mutex};
if (this->d_queue.empty())
return std::nullopt;
T rc(std::move(this->d_queue.front()));
this->d_queue.pop_front();
return {std::move(rc)};
}
};