7 #include <condition_variable>
34 : stop_waiting_{ false }
57 std::lock_guard<std::mutex> _(mutex_);
64 else if (limit_ != 0 && queue_.size() >= limit_) {
84 std::lock_guard<std::mutex> _(mutex_);
91 else if (limit_ != 0 && queue_.size() >= limit_) {
96 queue_.emplace(std::move(elem));
109 std::lock_guard<std::mutex> _(mutex_);
110 return PopInternal();
121 std::lock_guard<std::mutex> _(mutex_);
123 if (queue_.empty()) {
127 return queue_.front();
135 std::lock_guard<std::mutex> _(mutex_);
152 std::unique_lock<std::mutex> lock(mutex_);
153 cv_.wait(lock, [&]() {
return (stop_waiting_ || (queue_.size() > 0)); });
159 return PopInternal();
169 std::lock_guard<std::mutex> _(mutex_);
170 return queue_.size();
179 std::lock_guard<std::mutex> _(mutex_);
181 std::swap(queue_, empty);
190 bool Empty()
const {
return empty_; }
198 std::lock_guard<std::mutex> _(mutex_);
199 stop_waiting_ =
true;
211 std::lock_guard<std::mutex> _(mutex_);
223 std::optional<T> PopInternal()
225 if (queue_.empty()) {
230 auto elem = queue_.front();
233 if (queue_.empty()) {
245 void PopFrontInternal()
247 if (queue_.empty()) {
254 if (queue_.empty()) {
259 std::atomic<bool> empty_{
true };
262 std::condition_variable cv_;
264 std::queue<T> queue_;
Thread-safe FIFO queue with optional bounded, drop-oldest insertion.
Definition: safe_queue.h:26
bool Push(T &&elem)
Moves an element to the back, evicting the oldest element when at a nonzero limit.
Definition: safe_queue.h:80
bool Push(T const &elem)
Copies an element to the back of the queue.
Definition: safe_queue.h:53
~SafeQueue()
Wakes current waiters before destroying the queue; callers must ensure no operation remains active.
Definition: safe_queue.h:41
bool Empty() const
Check if queue is empty.
Definition: safe_queue.h:190
void StopWaiting()
Permanently causes current and future BlockPop() calls to return without waiting.
Definition: safe_queue.h:196
SafeQueue(uint32_t limit=5 '000)
Constructs an empty queue.
Definition: safe_queue.h:33
void SetLimit(uint32_t limit)
Changes the maximum retained element count.
Definition: safe_queue.h:209
void PopFront()
Removes the oldest object, or does nothing when empty.
Definition: safe_queue.h:133
void Clear()
Removes all elements without changing the limit or stopped-waiting state.
Definition: safe_queue.h:177
std::optional< T > Front()
Get first object without removing from queue.
Definition: safe_queue.h:119
std::optional< T > BlockPop()
Block waiting for data in queue, then remove the first object from queue (oldest object)
Definition: safe_queue.h:150
std::optional< T > Pop()
Remove the first object from queue (oldest object)
Definition: safe_queue.h:107
size_t Size()
Size of the queue.
Definition: safe_queue.h:167
Definition: attributes.h:13