pulsatrix
Loading...
Searching...
No Matches
bounded_queue.hpp
Go to the documentation of this file.
1
5#pragma once
6
7#include <condition_variable>
8#include <deque>
9#include <mutex>
10#include <optional>
11#include <utility>
12
13namespace pulsatrix {
14
25template <typename T>
27public:
28 explicit BoundedQueue(size_t capacity) : capacity_(capacity) {}
29
36 void push(T item) {
37 std::unique_lock<std::mutex> lock(mutex_);
38 not_full_.wait(lock, [this] { return closed_ || items_.size() < capacity_; });
39 if (closed_) {
40 return;
41 }
42 items_.push_back(std::move(item));
43 lock.unlock();
44 not_empty_.notify_one();
45 }
46
51 [[nodiscard]] std::optional<T> pop() {
52 std::unique_lock<std::mutex> lock(mutex_);
53 not_empty_.wait(lock, [this] { return closed_ || !items_.empty(); });
54 if (items_.empty()) {
55 return std::nullopt;
56 }
57 T item = std::move(items_.front());
58 items_.pop_front();
59 lock.unlock();
60 not_full_.notify_one();
61 return item;
62 }
63
65 void close() {
66 {
67 std::lock_guard<std::mutex> lock(mutex_);
68 closed_ = true;
69 }
70 not_empty_.notify_all();
71 not_full_.notify_all();
72 }
73
74private:
75 std::deque<T> items_;
76 size_t capacity_;
77 std::mutex mutex_;
78 std::condition_variable not_full_;
79 std::condition_variable not_empty_;
80 bool closed_ = false;
81};
82
83} // namespace pulsatrix
Fixed-capacity thread-safe queue with blocking push/pop – the bounded buffer between pulsatrix data-p...
Definition bounded_queue.hpp:26
void close()
Signals no more pushes will occur; unblocks every waiting push()/pop().
Definition bounded_queue.hpp:65
void push(T item)
Pushes an item, blocking while the queue is full.
Definition bounded_queue.hpp:36
std::optional< T > pop()
Pops the next item, blocking while the queue is empty and not closed.
Definition bounded_queue.hpp:51
BoundedQueue(size_t capacity)
Definition bounded_queue.hpp:28
Definition acquisition_functions.hpp:16