TEC
A lightweight C++ library enabling safe, efficient execution in multithreaded and concurrent systems.
Loading...
Searching...
No Matches
tec_queue.hpp
Go to the documentation of this file.
1// Time-stamp: <Last changed 2026-02-20 16:01:22 by magnolia>
2/*----------------------------------------------------------------------
3------------------------------------------------------------------------
4Copyright (c) 2020-2026 The Emacs Cat (https://github.com/olddeuteronomy/tec).
5
6 Licensed under the Apache License, Version 2.0 (the "License");
7 you may not use this file except in compliance with the License.
8 You may obtain a copy of the License at
9
10 http://www.apache.org/licenses/LICENSE-2.0
11
12 Unless required by applicable law or agreed to in writing, software
13 distributed under the License is distributed on an "AS IS" BASIS,
14 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 See the License for the specific language governing permissions and
16 limitations under the License.
17------------------------------------------------------------------------
18----------------------------------------------------------------------*/
31#pragma once
32
33#include <cstddef>
34#include <queue>
35#include <mutex>
36#include <condition_variable>
37
38#include "tec/tec_def.hpp" // IWYU pragma: keep
39
40
41namespace tec {
42
51template <class T>
52class SafeQueue {
53private:
54 std::queue<T> q_;
55 mutable std::mutex m_;
56 mutable std::condition_variable c_;
57
58public:
65 : q_{}
66 , m_{}
67 , c_{}
68 {}
69
75 ~SafeQueue(void) = default;
76
83 void enqueue(T&& t) {
84 std::lock_guard<std::mutex> lock(m_);
85 q_.push(std::move(t));
86 c_.notify_one();
87 }
88
95 T dequeue(void) {
96 std::unique_lock<std::mutex> lock(m_);
97 while (q_.empty()) {
98 // Release lock during wait and reacquire it afterwards.
99 c_.wait(lock);
100 }
101 T val = q_.front();
102 q_.pop();
103 return val;
104 }
105
111 std::size_t size() const {
112 std::unique_lock<std::mutex> lock(m_);
113 return q_.size();
114 }
115}; // class SafeQueue
116
117} // namespace tec
A thread-safe queue implementation for storing and retrieving elements of type T.
Definition tec_queue.hpp:52
void enqueue(T &&t)
Adds an element to the back of the queue.
Definition tec_queue.hpp:83
~SafeQueue(void)=default
Destructor for the SafeQueue.
SafeQueue(void)
Constructs an empty thread-safe queue.
Definition tec_queue.hpp:64
T dequeue(void)
Retrieves and removes the front element from the queue.
Definition tec_queue.hpp:95
std::size_t size() const
Returns the current number of elements in the queue.
Definition tec_queue.hpp:111
Common definitions and utilities for the tec namespace.