rsl 1.1.0
ROS Support Library
Loading...
Searching...
No Matches
queue.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <chrono>
4#include <condition_variable>
5#include <mutex>
6#include <optional>
7#include <queue>
8
9namespace rsl {
10
17template <typename T>
18class Queue {
19 std::queue<T> queue_;
20 std::condition_variable cv_;
21 mutable std::mutex mutex_;
22
23 public:
28 [[nodiscard]] auto size() const noexcept {
29 auto const lock = std::lock_guard(mutex_);
30 return queue_.size();
31 }
32
37 [[nodiscard]] auto empty() const noexcept {
38 auto const lock = std::lock_guard(mutex_);
39 return queue_.empty();
40 }
41
46 void push(T value) noexcept {
47 auto const lock = std::lock_guard(mutex_);
48 queue_.push(std::move(value));
49 cv_.notify_one();
50 }
51
55 void clear() noexcept {
56 auto const lock = std::lock_guard(mutex_);
57
58 // Swap queue with an empty queue of the same type to ensure queue_ is left in a
59 // default-constructed state
60 decltype(queue_)().swap(queue_);
61 }
62
68 [[nodiscard]] auto pop(std::chrono::nanoseconds wait_time = {}) -> std::optional<T> {
69 auto lock = std::unique_lock(mutex_);
70
71 // If queue is empty after wait_time, return nothing
72 if (!cv_.wait_for(lock, wait_time, [this] { return !queue_.empty(); })) return std::nullopt;
73
74 auto value = queue_.front();
75 queue_.pop();
76 return value;
77 }
78};
79} // namespace rsl
Thread-safe queue. Particularly useful when multiple threads need to write to and/or read from a queu...
Definition queue.hpp:18
void clear() noexcept
Clear the queue.
Definition queue.hpp:55
auto size() const noexcept
Get the size of the queue.
Definition queue.hpp:28
void push(T value) noexcept
Push data into the queue.
Definition queue.hpp:46
auto empty() const noexcept
Check if the queue is empty.
Definition queue.hpp:37
auto pop(std::chrono::nanoseconds wait_time={}) -> std::optional< T >
Wait for given duration then pop from the queue and return the element.
Definition queue.hpp:68