forked from PhotonVision/photon-libcamera-gl-driver
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconcurrent_blocking_queue.h
More file actions
57 lines (47 loc) · 1.34 KB
/
concurrent_blocking_queue.h
File metadata and controls
57 lines (47 loc) · 1.34 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
#pragma once
#include <condition_variable>
#include <mutex>
#include <optional>
#include <queue>
template <typename T> class ConcurrentBlockingQueue {
public:
ConcurrentBlockingQueue() = default;
T pop() {
std::unique_lock<std::mutex> lock(m_mutex);
m_cond.wait(lock, [&] { return !m_queue.empty(); });
auto item = std::move(m_queue.front());
m_queue.pop();
return item;
}
std::optional<T> try_pop() {
std::unique_lock<std::mutex> lock(m_mutex);
if (m_queue.empty()) {
return std::nullopt;
}
auto item = std::move(m_queue.front());
m_queue.pop();
return item;
}
void push(const T &item) {
std::unique_lock<std::mutex> lock(m_mutex);
m_queue.push(item);
lock.unlock();
m_cond.notify_one();
}
void push(T &&item) {
std::unique_lock<std::mutex> lock(m_mutex);
m_queue.push(std::forward<T>(item));
lock.unlock();
m_cond.notify_one();
}
template <typename... Args> void emplace(Args &&...args) {
std::unique_lock<std::mutex> lock(m_mutex);
m_queue.emplace(std::forward<Args>(args)...);
lock.unlock();
m_cond.notify_one();
}
private:
std::queue<T> m_queue;
std::mutex m_mutex;
std::condition_variable m_cond;
};