| 7 | #include <queue> |
| 8 | |
| 9 | template <typename T> class ThreadSafeQueue { |
| 10 | public: |
| 11 | explicit ThreadSafeQueue(size_t max_size = 8) |
| 12 | : max_size_(max_size) {} |
| 13 | |
| 14 | // Disable copy constructor and assignment operator |
| 15 | ThreadSafeQueue(const ThreadSafeQueue &) = delete; |
| 16 | ThreadSafeQueue &operator=(const ThreadSafeQueue &) = delete; |
| 17 | |
| 18 | // Return false when the queue is full. |
| 19 | bool push(T t) { |
| 20 | { |
| 21 | std::lock_guard<std::mutex> lock(mutex_); |
| 22 | if (queue_.size() >= max_size_) { |
| 23 | return false; |
| 24 | } |
| 25 | queue_.push(std::move(t)); |
| 26 | } |
| 27 | cv_.notify_one(); |
| 28 | return true; |
| 29 | } |
| 30 | |
| 31 | // blocking pop with timeout |
| 32 | std::optional<T> pop(int timeout_ms) { |
| 33 | std::unique_lock<std::mutex> lock(mutex_); |
| 34 | auto timeout = std::chrono::milliseconds(timeout_ms); |
| 35 | bool notified = cv_.wait_for(lock, timeout, [this] { |
| 36 | return !queue_.empty(); |
| 37 | }); |
| 38 | |
| 39 | if (!notified) { |
| 40 | return std::nullopt; |
| 41 | } |
| 42 | T t = std::move(queue_.front()); |
| 43 | queue_.pop(); |
| 44 | return t; |
| 45 | } |
| 46 | |
| 47 | // non-blocking pop |
| 48 | std::optional<T> pop() { |
| 49 | std::lock_guard<std::mutex> lock(mutex_); |
| 50 | if (queue_.empty()) { |
| 51 | return std::nullopt; |
| 52 | } |
| 53 | T t = std::move(queue_.front()); |
| 54 | queue_.pop(); |
| 55 | return t; |
| 56 | } |
| 57 | |
| 58 | std::optional<T> front() { |
| 59 | std::lock_guard<std::mutex> lock(mutex_); |
| 60 | if (queue_.empty()) { |
| 61 | return std::nullopt; |
| 62 | } |
| 63 | T t = queue_.front(); |
| 64 | return t; |
| 65 | } |
| 66 |
nothing calls this directly
no outgoing calls
no test coverage detected