HPC_Voxel_Engine 0.2.0
High-Performance C++ Voxel Engine
Loading...
Searching...
No Matches
ThreadSafeQueue.h
Go to the documentation of this file.
1#pragma once
2
3#include <atomic>
4#include <condition_variable>
5#include <mutex>
6#include <optional>
7#include <queue>
8
9namespace Core {
10
16template <typename T>
18public:
19 ThreadSafeQueue() = default;
22
26 void push(T&& objValue) {
27 {
28 std::scoped_lock objLock(m_objMutex);
29 m_queJobs.push(std::move(objValue));
30 }
31 m_objContVar.notify_one();
32 }
33
37 void push(const T& objValue) {
38 {
39 std::scoped_lock objLock(m_objMutex);
40 m_queJobs.push(objValue);
41 }
42 m_objContVar.notify_one();
43 }
44
50 bool wait_and_pop(T& objValue) {
51 std::unique_lock<std::mutex> objLock(m_objMutex);
52
53 // Wait until queue has items OR queue is invalidated (stopped)
54 m_objContVar.wait(objLock, [this] { return !m_queJobs.empty() || m_bInvalidated; });
55
56 if (m_bInvalidated && m_queJobs.empty()) {
57 return false;
58 }
59
60 objValue = std::move(m_queJobs.front());
61 m_queJobs.pop();
62
63 return true;
64 }
65
70 std::optional<T> try_pop() {
71 std::scoped_lock objLock(m_objMutex);
72 if (m_queJobs.empty()) {
73 return std::nullopt;
74 }
75 T objValue = std::move(m_queJobs.front());
76 m_queJobs.pop();
77 return objValue;
78 }
79
80 bool empty() const {
81 std::scoped_lock objLock(m_objMutex);
82 return m_queJobs.empty();
83 }
84
88 void invalidate() {
89 {
90 std::scoped_lock objLock(m_objMutex);
91 m_bInvalidated = true;
92 }
93 m_objContVar.notify_all();
94 }
95
96private:
97 std::queue<T> m_queJobs;
98 mutable std::mutex m_objMutex;
99 std::condition_variable m_objContVar;
100 std::atomic<bool> m_bInvalidated = false;
101};
102} // namespace Core
A thread-safe FIFO queue wrapper using mutexes and condition variables. Designed for producer-consume...
Definition ThreadSafeQueue.h:17
bool empty() const
Definition ThreadSafeQueue.h:80
ThreadSafeQueue & operator=(const ThreadSafeQueue &)=delete
void push(const T &objValue)
Pushes a value into the queue (Copy semantics).
Definition ThreadSafeQueue.h:37
void invalidate()
Wakes up all waiting threads effectively cancelling the wait.
Definition ThreadSafeQueue.h:88
bool wait_and_pop(T &objValue)
Waits until the queue is not empty, then pops the front element.
Definition ThreadSafeQueue.h:50
void push(T &&objValue)
Pushes a value into the queue (Move semantics).
Definition ThreadSafeQueue.h:26
ThreadSafeQueue(const ThreadSafeQueue &)=delete
std::queue< T > m_queJobs
Definition ThreadSafeQueue.h:97
std::optional< T > try_pop()
Non-blocking attempt to pop an item.
Definition ThreadSafeQueue.h:70
std::mutex m_objMutex
Definition ThreadSafeQueue.h:98
std::atomic< bool > m_bInvalidated
Definition ThreadSafeQueue.h:100
std::condition_variable m_objContVar
Definition ThreadSafeQueue.h:99
Definition camera.h:6