3#include <boost/circular_buffer.hpp>
4#include <condition_variable>
10#include "software/time/duration.h"
11#include "software/util/typename/typename.h"
103 std::unique_lock<std::mutex> waitForBufferToHaveAValue(
Duration max_wait_time);
105 std::mutex buffer_mutex;
106 boost::circular_buffer<T> buffer;
108 std::condition_variable received_new_value;
110 std::mutex destructor_called_mutex;
111 bool log_buffer_full;
112 bool destructor_called;
117 : buffer(buffer_size), log_buffer_full(log_buffer_full), destructor_called(false)
126 auto buffer_lock = waitForBufferToHaveAValue(max_wait_time);
128 std::optional<T> result = std::nullopt;
131 result = buffer.front();
142 auto buffer_lock = waitForBufferToHaveAValue(max_wait_time);
144 std::optional<T> result = std::nullopt;
147 result = buffer.back();
156 std::scoped_lock<std::mutex> buffer_lock(buffer_mutex);
157 if (log_buffer_full && buffer.full())
159 std::cerr <<
"Pushing to a full ThreadSafeBuffer of type: " << TYPENAME(T)
162 buffer.push_back(value);
163 received_new_value.notify_all();
170 std::unique_lock<std::mutex> buffer_lock(buffer_mutex);
171 received_new_value.wait_for(
172 buffer_lock, std::chrono::duration<float>(max_wait_time.
toSeconds()), [
this] {
173 std::scoped_lock destructor_called_lock(destructor_called_mutex);
174 return !buffer.empty() || destructor_called;
185 return buffer.empty();
191 destructor_called_mutex.lock();
192 destructor_called =
true;
193 destructor_called_mutex.unlock();
195 received_new_value.notify_all();
static const Duration fromSeconds(double seconds)
Definition duration.cpp:13
Definition thread_safe_buffer.hpp:23
std::optional< T > popMostRecentlyAddedValue(Duration max_wait_time=Duration::fromSeconds(0))
Definition thread_safe_buffer.hpp:138
std::optional< T > popLeastRecentlyAddedValue(Duration max_wait_time=Duration::fromSeconds(0))
Definition thread_safe_buffer.hpp:122
bool empty() const
Definition thread_safe_buffer.hpp:183
void push(const T &value)
Definition thread_safe_buffer.hpp:154
ThreadSafeBuffer(std::size_t buffer_size, bool log_buffer_full=true)
Definition thread_safe_buffer.hpp:116
double toSeconds() const
Definition time.cpp:12