Async++ unknown
Async (co_await/co_return) code for C++
Loading...
Searching...
No Matches
threadsafe_queue.h
1#pragma once
2#include <deque>
3#include <mutex>
4#include <optional>
5#include <queue>
6#include <utility>
7
8namespace asyncpp {
15 template<typename T, typename Container = std::deque<T>>
17 std::mutex m_mutex{};
18 std::queue<T, Container> m_queue{};
19
20 public:
25 template<typename... Args>
26 explicit threadsafe_queue(Args&&... args) : m_queue(std::forward<Args>(args)...) {}
27
29 std::scoped_lock lck{other.m_mutex};
30 m_queue = other.m_queue;
31 }
32 //NOLINTNEXTLINE(performance-noexcept-move-constructor)
34 std::scoped_lock lck{other.m_mutex};
35 m_queue = std::move(other.m_queue);
36 }
37 threadsafe_queue& operator=(const threadsafe_queue& other) {
38 if (&other != this) {
39 std::scoped_lock lck{other.m_mutex, m_mutex};
40 m_queue = other.m_queue;
41 }
42 return *this;
43 }
44 //NOLINTNEXTLINE(performance-noexcept-move-constructor)
45 threadsafe_queue& operator=(threadsafe_queue&& other) {
46 if (&other != this) {
47 std::scoped_lock lck{other.m_mutex, m_mutex};
48 m_queue = std::move(other.m_queue);
49 }
50 return *this;
51 }
52
57 std::optional<T> pop() {
58 std::scoped_lock lck{m_mutex};
59 if (m_queue.empty()) return std::nullopt;
60 auto entry = std::move(m_queue.front());
61 m_queue.pop();
62 return entry;
63 }
64
69 void push(T val) {
70 std::scoped_lock lck{m_mutex};
71 m_queue.push(std::move(val));
72 }
73
78 template<typename... Args>
79 void emplace(Args&&... args) {
80 std::scoped_lock lck{m_mutex};
81 m_queue.emplace(std::forward<Args>(args)...);
82 }
83 };
84} // namespace asyncpp
A threadsafe (mutex protected) queue.
Definition threadsafe_queue.h:16
void emplace(Args &&... args)
Emplace a new element to the queue.
Definition threadsafe_queue.h:79
void push(T val)
Push an element to the queue.
Definition threadsafe_queue.h:69
std::optional< T > pop()
Pop the first element from the queue.
Definition threadsafe_queue.h:57
threadsafe_queue(Args &&... args)
Construct a new queue.
Definition threadsafe_queue.h:26