From 6204c0ac95c97e61a01d1691bff39cfde7b35508 Mon Sep 17 00:00:00 2001 From: Lars Froehlich Date: Mon, 26 Oct 2026 14:36:13 +0100 Subject: [PATCH 01/18] Use clang-format config from DOOCS clientlib, serverlib [why] No good reason, except that this follows our style guide and it makes the code bases more consistent. --- .clang-format | 37 +++++++++++++++++++++++++++++++++---- 1 file changed, 33 insertions(+), 4 deletions(-) diff --git a/.clang-format b/.clang-format index 6cd501a6..bbc4da47 100644 --- a/.clang-format +++ b/.clang-format @@ -1,17 +1,46 @@ --- BasedOnStyle: WebKit -BreakBeforeBraces: Stroustrup -BreakConstructorInitializersBeforeComma: 'true' +BreakBeforeBraces: Custom +BraceWrapping: + AfterCaseLabel: true + AfterClass: true + AfterControlStatement: true + AfterEnum: true + AfterFunction: true + AfterNamespace: false + AfterObjCDeclaration: false + AfterStruct: true + AfterUnion: true + AfterExternBlock: false + BeforeCatch: true + BeforeElse: true + BeforeLambdaBody: true + BeforeWhile: true + IndentBraces: false + SplitEmptyFunction: true + SplitEmptyRecord: true + SplitEmptyNamespace: true +AlignConsecutiveMacros : true +AlignTrailingComments : true +AllowShortCaseLabelsOnASingleLine : false +AllowShortEnumsOnASingleLine : true +AllowShortFunctionsOnASingleLine : Inline +AllowShortLambdasOnASingleLine : All +AlwaysBreakTemplateDeclarations : Yes +BreakConstructorInitializersBeforeComma: true +BreakStringLiterals: false ColumnLimit: '90' FixNamespaceComments: 'true' IndentWidth: '4' KeepEmptyLinesAtTheStartOfBlocks: 'false' Language: Cpp MaxEmptyLinesToKeep: '2' -NamespaceIndentation: Inner +NamespaceIndentation: None PointerAlignment: Left ReflowComments: 'false' -Standard: Cpp11 +SortIncludes: false +SpaceBeforeCpp11BracedList : false +Standard: Latest UseTab: Never ... From c92b8ca8397c1b46fac2c818a695a9d4a694bc3b Mon Sep 17 00:00:00 2001 From: Lars Froehlich Date: Mon, 26 Oct 2026 14:46:48 +0100 Subject: [PATCH 02/18] Add ThreadSafeQueue class template This commit adds the ThreadSafeQueue class template. The original source code is taken from the Taskolib project: https://github.com/taskolib/taskolib The original class was called LockedQueue. I have adapted minor and obvious things like the namespace, include guards, and a part of the test suite. --- include/gul17/ThreadSafeQueue.h | 218 ++++++++++++++++++++++++++ include/gul17/meson.build | 1 + tests/meson.build | 1 + tests/test_ThreadSafeQueue.cc | 262 ++++++++++++++++++++++++++++++++ 4 files changed, 482 insertions(+) create mode 100644 include/gul17/ThreadSafeQueue.h create mode 100644 tests/test_ThreadSafeQueue.cc diff --git a/include/gul17/ThreadSafeQueue.h b/include/gul17/ThreadSafeQueue.h new file mode 100644 index 00000000..de850fd4 --- /dev/null +++ b/include/gul17/ThreadSafeQueue.h @@ -0,0 +1,218 @@ +/** + * \file ThreadSafeQueue.h + * \date Created on April 1, 2022 + * \brief Declaration of the ThreadSafeQueue class. + * + * \copyright Copyright 2022-2026 Deutsches Elektronen-Synchrotron (DESY), Hamburg + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published + * by the Free Software Foundation, either version 2.1 of the license, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +// SPDX-License-Identifier: LGPL-2.1-or-later + +#ifndef GUL17_THREADSAFEQUEUE_H_ +#define GUL17_THREADSAFEQUEUE_H_ + +#include +#include +#include + +#include "gul17/SlidingBuffer.h" + +namespace gul17 { + +/** + * A strictly bounded thread-safe message queue. + * + * Messages are added to the end of the queue with push() and taken from the start of the + * queue with pop(). These calls block if the queue is full or if no messages are + * available, respectively. try_push() and try_pop() are non-blocking alternatives. + * + * \code{.cpp} + * // Set up queue with capacity for 10 integers + * ThreadSafeQueue queue{ 10 }; + * + * // Start sender thread, pushing 100 integers into the queue + * std::thread sender([&queue]() + * { + * for (int i = 1; i <= 100; ++i) + * queue.push(i); + * }); + * + * // Pull all 100 integers out of the queue in the main thread + * for (int i = 1; i <= 100; ++i) + * { + * int val = queue.pop(); + * assert(val == i); + * } + * + * // Join the sender thread + * sender.join(); + * \endcode + */ +template +class ThreadSafeQueue +{ +public: + using MessageType = MessageT; + using message_type = MessageT; + using SizeType = std::size_t; + using size_type = SizeType; + + /// Construct a queue that is able to hold a given maximum number of entries. + ThreadSafeQueue(SizeType capacity) + : queue_(capacity) + { + } + + /** + * Fetch the last message from the queue and return a copy of it. + * The message is not removed from the queue. + * + * This call blocks until a message is available. + */ + MessageType back() const + { + std::unique_lock lock{ mutex_ }; + + if (queue_.empty()) + cv_message_available_.wait(lock, [this] { return not queue_.empty(); }); + + auto msg = queue_.back(); + lock.unlock(); + return msg; + } + + /// Return the maximal number of entries in the queue. + SizeType capacity() const + { + std::lock_guard lock{ mutex_ }; + return queue_.capacity(); + } + + /// Determine whether the queue is empty. + bool empty() const + { + std::lock_guard lock{ mutex_ }; + return queue_.empty(); + } + + /** + * Remove a message from the front of the queue and return it. + * + * This call blocks until a message is available. + * + * \see try_pop() + */ + MessageType pop() + { + std::unique_lock lock{ mutex_ }; + + if (queue_.empty()) + cv_message_available_.wait(lock, [this] { return not queue_.empty(); }); + + auto msg = std::move(queue_.front()); + queue_.pop_front(); + lock.unlock(); + cv_slot_available_.notify_one(); + return msg; + } + + /** + * Insert a message at the end of the queue. + * + * This call blocks until the queue has a free slot for the message. + */ + template , bool> = true> + void push(MsgT&& msg) + { + std::unique_lock lock{ mutex_ }; + + if (queue_.filled()) + cv_slot_available_.wait(lock, [this] { return not queue_.filled(); }); + + queue_.push_back(std::forward(msg)); + lock.unlock(); + cv_message_available_.notify_one(); + } + + /// Return the number of messages in the queue. + SizeType size() const + { + std::lock_guard lock{ mutex_ }; + return queue_.size(); + } + + /** + * Remove a message from the front of the queue and return it. + * + * This call blocks until a message is available. + * + * \see try_pop() + */ + std::optional try_pop() + { + std::unique_lock lock{ mutex_ }; + + if (queue_.empty()) + return std::nullopt; + + auto msg = std::move(queue_.front()); + queue_.pop_front(); + lock.unlock(); + cv_slot_available_.notify_one(); + return msg; + } + + /** + * Try to insert a message at the end of the queue. + * + * This call returns true if the message was successfully enqueued or false if the + * queue temporarily had no space to store the message. + * + * Messages given as an rvalue are only moved from if they can actually be inserted + * into the queue. + */ + template , bool> = true> + bool try_push(MsgT&& msg) + { + std::unique_lock lock{ mutex_ }; + + if (queue_.filled()) + return false; + + queue_.push_back(std::forward(msg)); + lock.unlock(); + cv_message_available_.notify_one(); + return true; + } + +private: + /// Mutex protecting all member variables + mutable std::mutex mutex_; + + /// Condition variable, triggered when at least one message has been added to the queue. + mutable std::condition_variable cv_message_available_; + + /// Condition variable, triggered when at least one slot in the queue has been freed. + mutable std::condition_variable cv_slot_available_; + + gul17::SlidingBuffer queue_; +}; + +} // namespace gul17 + +#endif diff --git a/include/gul17/meson.build b/include/gul17/meson.build index db7f45e5..fe34a778 100644 --- a/include/gul17/meson.build +++ b/include/gul17/meson.build @@ -20,6 +20,7 @@ standalone_headers = [ 'string_util.h', 'substring_checks.h', 'ThreadPool.h', + 'ThreadSafeQueue.h', 'time_util.h', 'to_number.h', 'tokenize.h', diff --git a/tests/meson.build b/tests/meson.build index 70a87948..6baeebaa 100644 --- a/tests/meson.build +++ b/tests/meson.build @@ -38,6 +38,7 @@ tests = [ 'test_string_util.cc', 'test_substring_checks.cc', 'test_ThreadPool.cc', + 'test_ThreadSafeQueue.cc', 'test_time_util.cc', 'test_to_number.cc', 'test_tokenize.cc', diff --git a/tests/test_ThreadSafeQueue.cc b/tests/test_ThreadSafeQueue.cc new file mode 100644 index 00000000..c4df60bb --- /dev/null +++ b/tests/test_ThreadSafeQueue.cc @@ -0,0 +1,262 @@ +/** + * \file test_ThreadSafeQueue.cc + * \date Created on April 1, 2022 + * \brief Test suite for the ThreadSafeQueue class template. + * + * \copyright Copyright 2022-2026 Deutsches Elektronen-Synchrotron (DESY), Hamburg + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published + * by the Free Software Foundation, either version 2.1 of the license, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +// SPDX-License-Identifier: LGPL-2.1-or-later + +#include +#include + +#include +#include + +#include "gul17/ThreadSafeQueue.h" +#include "gul17/time_util.h" + +using namespace gul17; + +namespace { + +struct Message +{ + int value_; + + Message(int v = 0) + : value_{ v } + { + } +}; + +} // anonymous namespace + +TEMPLATE_TEST_CASE("ThreadSafeQueue: Constructor", "[ThreadSafeQueue]", int, std::string, + Message, std::unique_ptr) +{ + static_assert(std::is_constructible, uint32_t>::value, + "ThreadSafeQueue is constructible"); + + ThreadSafeQueue queue{ 4 }; +} + +TEST_CASE("ThreadSafeQueue: back()", "[ThreadSafeQueue]") +{ + ThreadSafeQueue queue{ 2 }; + + queue.push(Message(1)); + auto msg_1 = queue.back(); + REQUIRE(queue.size() == 1); + REQUIRE(msg_1.value_ == 1); + + queue.push(Message(2)); + REQUIRE(queue.size() == 2); + auto msg_2 = queue.back(); + REQUIRE(queue.size() == 2); + REQUIRE(msg_2.value_ == 2); + + auto msg_pop = queue.pop(); + REQUIRE(queue.size() == 1); + REQUIRE(msg_pop.value_ == 1); + auto msg_back = queue.back(); + REQUIRE(queue.size() == 1); + REQUIRE(msg_back.value_ == 2); +} + +TEST_CASE("ThreadSafeQueue: capacity()", "[ThreadSafeQueue]") +{ + ThreadSafeQueue queue(42); + REQUIRE(queue.capacity() == 42u); +} + +TEMPLATE_TEST_CASE("ThreadSafeQueue: empty()", "[ThreadSafeQueue]", int, std::string, + Message, std::unique_ptr) +{ + ThreadSafeQueue queue{ 10 }; + REQUIRE(queue.empty() == true); + + queue.push(TestType{}); + REQUIRE(queue.empty() == false); + + queue.pop(); + REQUIRE(queue.empty() == true); +} + +TEMPLATE_TEST_CASE("ThreadSafeQueue: pop() single-threaded", "[ThreadSafeQueue]", int, + std::string, Message, std::unique_ptr) +{ + ThreadSafeQueue queue{ 10 }; + REQUIRE(queue.size() == 0); + + queue.push(TestType{}); + queue.push(TestType{}); + REQUIRE(queue.size() == 2u); + + queue.pop(); + REQUIRE(queue.size() == 1u); + + queue.pop(); + REQUIRE(queue.size() == 0); +} + +TEST_CASE("ThreadSafeQueue: push() single-threaded", "[ThreadSafeQueue]") +{ + ThreadSafeQueue queue{ 10 }; + REQUIRE(queue.size() == 0); + + queue.push(Message(42)); + REQUIRE(queue.size() == 1u); + + queue.push(Message(43)); + REQUIRE(queue.size() == 2u); + + auto msg = queue.pop(); + REQUIRE(queue.size() == 1u); + REQUIRE(msg.value_ == 42); + + msg = queue.pop(); + REQUIRE(queue.size() == 0); + REQUIRE(msg.value_ == 43); +} + +TEST_CASE("ThreadSafeQueue: push() & pop() across threads", "[ThreadSafeQueue]") +{ + // Create a queue with only 4 slots + ThreadSafeQueue queue{ 4 }; + + // Start a thread that will push 100 messages into the queue + std::thread sender( + [&queue]() + { + for (int i = 1; i <= 100; ++i) + queue.push(Message(i)); + }); + + gul17::sleep(0.005); + // Pull all 100 messages out of the queue from the main thread + for (int i = 1; i <= 100; ++i) + { + auto msg = queue.pop(); + REQUIRE(msg.value_ == i); + } + + sender.join(); +} + +TEST_CASE("ThreadSafeQueue: size()", "[ThreadSafeQueue]") +{ + ThreadSafeQueue queue{ 10 }; + REQUIRE(queue.size() == 0); + + queue.push(Message{}); + REQUIRE(queue.size() == 1u); + + queue.push(Message{}); + REQUIRE(queue.size() == 2u); + + queue.pop(); + REQUIRE(queue.size() == 1u); + + queue.pop(); + REQUIRE(queue.size() == 0); +} + +TEST_CASE("ThreadSafeQueue: try_pop() single-threaded", "[ThreadSafeQueue]") +{ + ThreadSafeQueue queue{ 2 }; + REQUIRE(queue.size() == 0); + + REQUIRE(queue.try_pop() == std::nullopt); + + queue.push(1); + queue.push(2); + REQUIRE(queue.size() == 2u); + + auto opt = queue.try_pop(); + REQUIRE(opt.has_value()); + REQUIRE(*opt == 1); + + opt = queue.try_pop(); + REQUIRE(opt.has_value()); + REQUIRE(*opt == 2); + + REQUIRE(queue.try_pop() == std::nullopt); +} + +TEST_CASE("ThreadSafeQueue: try_push() single-threaded", "[ThreadSafeQueue]") +{ + ThreadSafeQueue queue{ 2 }; + REQUIRE(queue.size() == 0); + + REQUIRE(queue.try_push(1) == true); + REQUIRE(queue.size() == 1u); + + REQUIRE(queue.try_push(2) == true); + REQUIRE(queue.size() == 2u); + + REQUIRE(queue.try_push(3) == false); // queue full + REQUIRE(queue.size() == 2u); + + int msg = queue.pop(); + REQUIRE(queue.size() == 1u); + REQUIRE(msg == 1); + + REQUIRE(queue.try_push(3) == true); + REQUIRE(queue.size() == 2u); + + msg = queue.pop(); + REQUIRE(queue.size() == 1u); + REQUIRE(msg == 2); + + msg = queue.pop(); + REQUIRE(queue.empty() == true); + REQUIRE(msg == 3); +} + +TEST_CASE("ThreadSafeQueue: try_push() & try_pop() across threads", "[ThreadSafeQueue]") +{ + // Create a queue with only 4 slots + ThreadSafeQueue queue{ 4 }; + + // Start a thread that will push 100 messages into the queue + std::thread sender( + [&queue]() + { + for (int i = 1; i <= 100; ++i) + { + while (queue.try_push(Message(i)) == false) + ; + } + }); + + // Pull all 100 messages out of the queue from the main thread + for (int i = 1; i <= 100; ++i) + { + std::optional opt_msg; + do + { + opt_msg = queue.try_pop(); + } + while (not opt_msg.has_value()); + + auto msg = *opt_msg; + REQUIRE(msg.value_ == i); + } + + sender.join(); +} From 05f3617e5ad88e2198653d13290b0be74f6019db Mon Sep 17 00:00:00 2001 From: Lars Froehlich Date: Mon, 26 Oct 2026 14:53:12 +0100 Subject: [PATCH 03/18] Update author list [why] Marcus is one of the original authors of Taskolib's LockedQueue. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index fa3055a6..f8d37f6e 100644 --- a/README.md +++ b/README.md @@ -197,7 +197,7 @@ This is not semantic versioning. The following individuals contributed to the General Utility Library: -> Jan Behrens, Lars Fröhlich, Sören Grunewald, Olaf Hensler, Fini Jastrow +> Jan Behrens, Lars Fröhlich, Sören Grunewald, Olaf Hensler, Fini Jastrow, Marcus Walla Additional code distributed with this library was written by the authors listed below. From 54bd38f8265293d1d84d93282f8d90907ddc322d Mon Sep 17 00:00:00 2001 From: Lars Froehlich Date: Mon, 26 Oct 2026 15:06:18 +0100 Subject: [PATCH 04/18] Change ThreadSafeQueue license to MIT [why] To match the license of GUL17. [how] All original authors have consented, so I have added the usual MIT Doxygen header to the files. --- include/gul17/ThreadSafeQueue.h | 26 ++++++++++++++------------ tests/test_ThreadSafeQueue.cc | 26 ++++++++++++++------------ 2 files changed, 28 insertions(+), 24 deletions(-) diff --git a/include/gul17/ThreadSafeQueue.h b/include/gul17/ThreadSafeQueue.h index de850fd4..9436c965 100644 --- a/include/gul17/ThreadSafeQueue.h +++ b/include/gul17/ThreadSafeQueue.h @@ -5,22 +5,24 @@ * * \copyright Copyright 2022-2026 Deutsches Elektronen-Synchrotron (DESY), Hamburg * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published - * by the Free Software Foundation, either version 2.1 of the license, or - * (at your option) any later version. + * Permission is hereby granted, free of charge, to any person obtaining a copy of this + * software and associated documentation files (the "Software"), to deal in the Software + * without restriction, including without limitation the rights to use, copy, modify, + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to the following + * conditions: * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. + * The above copyright notice and this permission notice shall be included in all copies + * or substantial portions of the Software. * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR + * THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -// SPDX-License-Identifier: LGPL-2.1-or-later - #ifndef GUL17_THREADSAFEQUEUE_H_ #define GUL17_THREADSAFEQUEUE_H_ diff --git a/tests/test_ThreadSafeQueue.cc b/tests/test_ThreadSafeQueue.cc index c4df60bb..a05aea60 100644 --- a/tests/test_ThreadSafeQueue.cc +++ b/tests/test_ThreadSafeQueue.cc @@ -5,22 +5,24 @@ * * \copyright Copyright 2022-2026 Deutsches Elektronen-Synchrotron (DESY), Hamburg * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published - * by the Free Software Foundation, either version 2.1 of the license, or - * (at your option) any later version. + * Permission is hereby granted, free of charge, to any person obtaining a copy of this + * software and associated documentation files (the "Software"), to deal in the Software + * without restriction, including without limitation the rights to use, copy, modify, + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to the following + * conditions: * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. + * The above copyright notice and this permission notice shall be included in all copies + * or substantial portions of the Software. * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR + * THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -// SPDX-License-Identifier: LGPL-2.1-or-later - #include #include From 230c1cd842e4fb7c68600f64020951f58d13ed9e Mon Sep 17 00:00:00 2001 From: Lars Froehlich Date: Mon, 26 Oct 2026 15:20:40 +0100 Subject: [PATCH 05/18] Reject zero queue length [why] A queue with zero entries does not make sense. [how] Throw std::invalid_argument when constructing ThreadSafeQueue{ 0 }. --- include/gul17/ThreadSafeQueue.h | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/include/gul17/ThreadSafeQueue.h b/include/gul17/ThreadSafeQueue.h index 9436c965..8e56109e 100644 --- a/include/gul17/ThreadSafeQueue.h +++ b/include/gul17/ThreadSafeQueue.h @@ -29,6 +29,7 @@ #include #include #include +#include #include "gul17/SlidingBuffer.h" @@ -72,10 +73,19 @@ class ThreadSafeQueue using SizeType = std::size_t; using size_type = SizeType; - /// Construct a queue that is able to hold a given maximum number of entries. + /** + * Construct a queue that is able to hold a given maximum number of entries. + * \param capacity The maximum number of entries the queue can hold + * \exception std::invalid_argument is thrown if the capacity is zero. + */ ThreadSafeQueue(SizeType capacity) : queue_(capacity) { + if (capacity == 0) + { + throw std::invalid_argument( + "ThreadSafeQueue capacity must be greater than 0"); + } } /** From de22a2398bc4c8b19c5681e950ceb9815bb592a8 Mon Sep 17 00:00:00 2001 From: Lars Froehlich Date: Mon, 26 Oct 2026 17:15:38 +0100 Subject: [PATCH 06/18] Add missing standard library includes --- include/gul17/ThreadSafeQueue.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/include/gul17/ThreadSafeQueue.h b/include/gul17/ThreadSafeQueue.h index 8e56109e..756f876c 100644 --- a/include/gul17/ThreadSafeQueue.h +++ b/include/gul17/ThreadSafeQueue.h @@ -30,6 +30,8 @@ #include #include #include +#include +#include #include "gul17/SlidingBuffer.h" From ee4784f585c3694271dc4cbfea5042c73e3df3c5 Mon Sep 17 00:00:00 2001 From: Lars Froehlich Date: Mon, 26 Oct 2026 17:16:46 +0100 Subject: [PATCH 07/18] Correct documentation of try_pop() --- include/gul17/ThreadSafeQueue.h | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/include/gul17/ThreadSafeQueue.h b/include/gul17/ThreadSafeQueue.h index 756f876c..55ff9ef3 100644 --- a/include/gul17/ThreadSafeQueue.h +++ b/include/gul17/ThreadSafeQueue.h @@ -170,11 +170,10 @@ class ThreadSafeQueue } /** - * Remove a message from the front of the queue and return it. - * - * This call blocks until a message is available. + * If a message is available, remove it from the front of the queue and return it; + * otherwise, return an empty optional. * - * \see try_pop() + * \see pop() */ std::optional try_pop() { From b056e0932281ee98648cfdd836f7c7658a2736ef Mon Sep 17 00:00:00 2001 From: Lars Froehlich Date: Mon, 26 Oct 2026 17:19:33 +0100 Subject: [PATCH 08/18] Make ThreadSafeQueue explicitly non-copy/movable [why] The class already was non-copyable and non-movable before because of its mutex and cv members. [how] Document non-copy/movability in the class documentation and explicitly delete all special member functions (rule of five). --- include/gul17/ThreadSafeQueue.h | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/include/gul17/ThreadSafeQueue.h b/include/gul17/ThreadSafeQueue.h index 55ff9ef3..a71302b7 100644 --- a/include/gul17/ThreadSafeQueue.h +++ b/include/gul17/ThreadSafeQueue.h @@ -65,6 +65,9 @@ namespace gul17 { * // Join the sender thread * sender.join(); * \endcode + * + * A ThreadSafeQueue is a synchronization tool for multiple threads. As such, it cannot be + * copied or moved. */ template class ThreadSafeQueue @@ -90,6 +93,12 @@ class ThreadSafeQueue } } + ~ThreadSafeQueue() = default; + ThreadSafeQueue(const ThreadSafeQueue&) = delete; + ThreadSafeQueue(ThreadSafeQueue&&) = delete; + ThreadSafeQueue& operator=(const ThreadSafeQueue&) = delete; + ThreadSafeQueue& operator=(ThreadSafeQueue&&) = delete; + /** * Fetch the last message from the queue and return a copy of it. * The message is not removed from the queue. From 40e696c4977f2878118f60bcf8e84a7424771d9b Mon Sep 17 00:00:00 2001 From: Lars Froehlich Date: Mon, 26 Oct 2026 17:23:35 +0100 Subject: [PATCH 09/18] Simplify condition variable wait() code [why] In several cases, wait() with a predicate is defined to execute exactly the check that we explicitly wrote out in the preceding if condition. This makes the if redundant. --- include/gul17/ThreadSafeQueue.h | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/include/gul17/ThreadSafeQueue.h b/include/gul17/ThreadSafeQueue.h index a71302b7..fe5902ee 100644 --- a/include/gul17/ThreadSafeQueue.h +++ b/include/gul17/ThreadSafeQueue.h @@ -108,9 +108,7 @@ class ThreadSafeQueue MessageType back() const { std::unique_lock lock{ mutex_ }; - - if (queue_.empty()) - cv_message_available_.wait(lock, [this] { return not queue_.empty(); }); + cv_message_available_.wait(lock, [this] { return not queue_.empty(); }); auto msg = queue_.back(); lock.unlock(); @@ -141,9 +139,7 @@ class ThreadSafeQueue MessageType pop() { std::unique_lock lock{ mutex_ }; - - if (queue_.empty()) - cv_message_available_.wait(lock, [this] { return not queue_.empty(); }); + cv_message_available_.wait(lock, [this] { return not queue_.empty(); }); auto msg = std::move(queue_.front()); queue_.pop_front(); @@ -162,9 +158,7 @@ class ThreadSafeQueue void push(MsgT&& msg) { std::unique_lock lock{ mutex_ }; - - if (queue_.filled()) - cv_slot_available_.wait(lock, [this] { return not queue_.filled(); }); + cv_slot_available_.wait(lock, [this] { return not queue_.filled(); }); queue_.push_back(std::forward(msg)); lock.unlock(); From 0ba0d33392d5fa3ebc5d46e8e151e5e2fc20bcfe Mon Sep 17 00:00:00 2001 From: Lars Froehlich Date: Mon, 26 Oct 2026 17:49:08 +0100 Subject: [PATCH 10/18] Document that the user is responsible for shutdown [why] If left to their own devices, threads might still be blocked on pop() while the application is shutting down. [how] Add an explanation to the class documentation that it is in the user's responsibility to shut down all threads cleanly. --- include/gul17/ThreadSafeQueue.h | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/include/gul17/ThreadSafeQueue.h b/include/gul17/ThreadSafeQueue.h index fe5902ee..de4ae83d 100644 --- a/include/gul17/ThreadSafeQueue.h +++ b/include/gul17/ThreadSafeQueue.h @@ -67,7 +67,9 @@ namespace gul17 { * \endcode * * A ThreadSafeQueue is a synchronization tool for multiple threads. As such, it cannot be - * copied or moved. + * copied or moved. It also has no built-in termination mechanism: The user must make sure + * that all threads using the queue can shut down properly; typically, this is done by + * sending a special termination message through the queue. */ template class ThreadSafeQueue From 0d267f8170214877918bcfe727f8649b586484fa Mon Sep 17 00:00:00 2001 From: Lars Froehlich Date: Mon, 26 Oct 2026 17:51:28 +0100 Subject: [PATCH 11/18] Improve thread and exception safety of back() [why] back() consumes a "message available" notification, but actually does not remove a message from the queue. If we use notify_one() for the notification, another waiting thread does not get the notification. [how] Use notify_all() to issue the notification. Also, document the behavior of the various push() and pop() functions in case of exceptions. --- include/gul17/ThreadSafeQueue.h | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/include/gul17/ThreadSafeQueue.h b/include/gul17/ThreadSafeQueue.h index de4ae83d..6dd9b64e 100644 --- a/include/gul17/ThreadSafeQueue.h +++ b/include/gul17/ThreadSafeQueue.h @@ -112,9 +112,7 @@ class ThreadSafeQueue std::unique_lock lock{ mutex_ }; cv_message_available_.wait(lock, [this] { return not queue_.empty(); }); - auto msg = queue_.back(); - lock.unlock(); - return msg; + return queue_.back(); } /// Return the maximal number of entries in the queue. @@ -136,6 +134,10 @@ class ThreadSafeQueue * * This call blocks until a message is available. * + * \exception + * If the move constructor of the message throws, the exception is rethrown and the + * element remains in the queue. + * * \see try_pop() */ MessageType pop() @@ -154,6 +156,10 @@ class ThreadSafeQueue * Insert a message at the end of the queue. * * This call blocks until the queue has a free slot for the message. + * + * \exception + * If the move or copy assignment of the message throws, the exception is rethrown + * and no message is inserted. */ template , bool> = true> @@ -164,7 +170,7 @@ class ThreadSafeQueue queue_.push_back(std::forward(msg)); lock.unlock(); - cv_message_available_.notify_one(); + cv_message_available_.notify_all(); } /// Return the number of messages in the queue. @@ -178,6 +184,10 @@ class ThreadSafeQueue * If a message is available, remove it from the front of the queue and return it; * otherwise, return an empty optional. * + * \exception + * If the move constructor of the message throws, the exception is rethrown and the + * element remains in the queue. + * * \see pop() */ std::optional try_pop() @@ -202,6 +212,10 @@ class ThreadSafeQueue * * Messages given as an rvalue are only moved from if they can actually be inserted * into the queue. + * + * \exception + * If the move or copy assignment of the message throws, the exception is rethrown + * and no message is inserted. */ template , bool> = true> @@ -214,7 +228,7 @@ class ThreadSafeQueue queue_.push_back(std::forward(msg)); lock.unlock(); - cv_message_available_.notify_one(); + cv_message_available_.notify_all(); return true; } From 96d59f03f03050c58c3358709165ec1f8230b587 Mon Sep 17 00:00:00 2001 From: Lars Froehlich Date: Mon, 26 Oct 2026 18:40:11 +0100 Subject: [PATCH 12/18] Pre-construct an optional in try_pop() [why] What we constructed before by moving from the queue was a T, not an optional. This made it somewhat inefficient to return it from the function. [how] Directly construct an optional from the moved queue element. This is then a candidate for NRVO. --- include/gul17/ThreadSafeQueue.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/gul17/ThreadSafeQueue.h b/include/gul17/ThreadSafeQueue.h index 6dd9b64e..c9547453 100644 --- a/include/gul17/ThreadSafeQueue.h +++ b/include/gul17/ThreadSafeQueue.h @@ -197,7 +197,7 @@ class ThreadSafeQueue if (queue_.empty()) return std::nullopt; - auto msg = std::move(queue_.front()); + auto msg = std::optional{ std::move(queue_.front()) }; queue_.pop_front(); lock.unlock(); cv_slot_available_.notify_one(); From 4ffb2fc8af3551dd0fe25c4b645fa4935e5c9c86 Mon Sep 17 00:00:00 2001 From: Lars Froehlich Date: Mon, 26 Oct 2026 18:42:16 +0100 Subject: [PATCH 13/18] Re-issue "slot available" notification if push() throws [why] We use notify_one() to notify push() waiters of a free slot. If the push_back() throws, the notification has been consumed but the slot is still free. We should notify the next waiting thread, if any. [how] Catch exceptions thrown by push_back(). If one occurs, re-issue the notification and rethrow the exception. --- include/gul17/ThreadSafeQueue.h | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/include/gul17/ThreadSafeQueue.h b/include/gul17/ThreadSafeQueue.h index c9547453..39be9738 100644 --- a/include/gul17/ThreadSafeQueue.h +++ b/include/gul17/ThreadSafeQueue.h @@ -168,7 +168,18 @@ class ThreadSafeQueue std::unique_lock lock{ mutex_ }; cv_slot_available_.wait(lock, [this] { return not queue_.filled(); }); - queue_.push_back(std::forward(msg)); + try + { + queue_.push_back(std::forward(msg)); + } + catch (...) + { + // Forward the "slot available" notification to another waiting thread. + lock.unlock(); + cv_slot_available_.notify_one(); + throw; + } + lock.unlock(); cv_message_available_.notify_all(); } From 166ee69f123e76625241347da40fb0fd29740ce3 Mon Sep 17 00:00:00 2001 From: Lars Froehlich Date: Mon, 26 Oct 2026 18:58:08 +0100 Subject: [PATCH 14/18] Add ThreadSafeQueue to documentation overviews --- data/doxygen.h | 12 ++++++++++++ include/gul17/ThreadSafeQueue.h | 2 ++ 2 files changed, 14 insertions(+) diff --git a/data/doxygen.h b/data/doxygen.h index 1c06189b..834a3121 100644 --- a/data/doxygen.h +++ b/data/doxygen.h @@ -150,6 +150,10 @@ namespace gul17 { * * \section changelog_gul17 GUL17 Versions * + * \subsection UNRELEASED Unreleased + * + * - Add ThreadSafeQueue class + * * \subsection V26_10_0 Version 26.10.0 * * - The library is now licensed under the MIT license. For more details, please refer to @@ -469,6 +473,10 @@ namespace gul17 { * *

Classes

* + * \ref gul17::ThreadSafeQueue "ThreadSafeQueue": + * A thread-safe queue with fixed maximum capacity for sending messages between + * threads. + * * \ref gul17::ThreadPool "ThreadPool": * A thread pool and task queue that allows executing tasks on a fixed number of * worker threads. @@ -738,6 +746,10 @@ namespace gul17 { * A resizable container with contiguous storage that can hold a specified number of * elements without allocating memory on the heap. * + * ThreadSafeQueue: + * A thread-safe queue with fixed maximum capacity for sending messages between + * threads. + * *

Single-Element and Special-Purpose Containers

* * \ref gul17::expected "expected": diff --git a/include/gul17/ThreadSafeQueue.h b/include/gul17/ThreadSafeQueue.h index 39be9738..b6d9bf98 100644 --- a/include/gul17/ThreadSafeQueue.h +++ b/include/gul17/ThreadSafeQueue.h @@ -70,6 +70,8 @@ namespace gul17 { * copied or moved. It also has no built-in termination mechanism: The user must make sure * that all threads using the queue can shut down properly; typically, this is done by * sending a special termination message through the queue. + * + * \since version UNRELEASED */ template class ThreadSafeQueue From ea04cdea7b6e11bf6369bcf140cd9467c108d939 Mon Sep 17 00:00:00 2001 From: Lars Froehlich Date: Wed, 28 Oct 2026 09:24:29 +0100 Subject: [PATCH 15/18] ThreadSafeQueue: Improve class documentation This adds some explanation of the design (mutexes and condition variables) and under which conditions the queue is expected to perform well. We also document that the message type must be default-constructible and movable in general, and copy-constructible if back() is used. --- include/gul17/ThreadSafeQueue.h | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/include/gul17/ThreadSafeQueue.h b/include/gul17/ThreadSafeQueue.h index b6d9bf98..64ce6727 100644 --- a/include/gul17/ThreadSafeQueue.h +++ b/include/gul17/ThreadSafeQueue.h @@ -38,11 +38,18 @@ namespace gul17 { /** - * A strictly bounded thread-safe message queue. + * A strictly bounded thread-safe message queue for N producers and M consumers that is + * not lock-free. * - * Messages are added to the end of the queue with push() and taken from the start of the - * queue with pop(). These calls block if the queue is full or if no messages are - * available, respectively. try_push() and try_pop() are non-blocking alternatives. + * The queue uses mutexes and condition variables to synchronize access between multiple + * producers and consumers. It typically performs well under low contention (low numbers + * of producers and consumers, reasonably low message rate) but may not be the optimal + * choice for low-latency applications. + * + * Messages may be of any type that is default-constructible and movable. They are added + * to the end of the queue with push() and taken from the start of the queue with pop(). + * These calls block if the queue is full or if no messages are available, respectively. + * try_push() and try_pop() are non-blocking alternatives. * * \code{.cpp} * // Set up queue with capacity for 10 integers @@ -66,10 +73,14 @@ namespace gul17 { * sender.join(); * \endcode * + * For convenience, the queue also provides a back() member function that blocks until a + * message is available and then returns a copy of the last message without removing it + * from the queue. Obviously, use of back() requires the message type to be copyable. + * * A ThreadSafeQueue is a synchronization tool for multiple threads. As such, it cannot be * copied or moved. It also has no built-in termination mechanism: The user must make sure * that all threads using the queue can shut down properly; typically, this is done by - * sending a special termination message through the queue. + * sending one or more special termination messages through the queue. * * \since version UNRELEASED */ @@ -108,6 +119,9 @@ class ThreadSafeQueue * The message is not removed from the queue. * * This call blocks until a message is available. + * + * \note + * Obviously, this function requires the message to be copyable. */ MessageType back() const { From 78cec6ff8db3f8dddcae116aed27d05ad7f31280 Mon Sep 17 00:00:00 2001 From: Lars Froehlich Date: Wed, 28 Oct 2026 09:26:06 +0100 Subject: [PATCH 16/18] static_assert default-ctor and movability of MessageT [why] The queue expects its message type to be default-constructible (see SlidingBuffer), move-constructible and move-assignable. back() expects the type to by copy-constructible. --- include/gul17/ThreadSafeQueue.h | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/include/gul17/ThreadSafeQueue.h b/include/gul17/ThreadSafeQueue.h index 64ce6727..f3347687 100644 --- a/include/gul17/ThreadSafeQueue.h +++ b/include/gul17/ThreadSafeQueue.h @@ -88,6 +88,13 @@ template class ThreadSafeQueue { public: + static_assert(std::is_default_constructible_v, + "Message type must be default-constructible"); + static_assert(std::is_move_constructible_v, + "Message type must be move-constructible"); + static_assert( + std::is_move_assignable_v, "Message type must be move-assignable"); + using MessageType = MessageT; using message_type = MessageT; using SizeType = std::size_t; @@ -125,6 +132,9 @@ class ThreadSafeQueue */ MessageType back() const { + static_assert(std::is_copy_constructible_v, + "Message type must be copy-constructible to use back()"); + std::unique_lock lock{ mutex_ }; cv_message_available_.wait(lock, [this] { return not queue_.empty(); }); From 71246d1894ead2a1f78a384e510d06a47f264b10 Mon Sep 17 00:00:00 2001 From: Lars Froehlich Date: Wed, 28 Oct 2026 10:36:32 +0100 Subject: [PATCH 17/18] Add try_pop() and pop() overloads returning by reference [why] Sometimes there are use cases where messages should be directly assigned to an existing object instead of returning by value. Overloads allowing this also offer slightly better exception guarantees than the return-by-value versions in the case of a throwing move operation. [how] Add new overloads bool try_pop(MessageType& msg) pop(MessageType& msg) and improve the exception safety documentation of pop() and try_pop() to be as accurate as possible about what users can expect if their type throws upon move. --- include/gul17/ThreadSafeQueue.h | 84 ++++++++++++++++++++++++++++----- 1 file changed, 72 insertions(+), 12 deletions(-) diff --git a/include/gul17/ThreadSafeQueue.h b/include/gul17/ThreadSafeQueue.h index f3347687..625d8f68 100644 --- a/include/gul17/ThreadSafeQueue.h +++ b/include/gul17/ThreadSafeQueue.h @@ -160,11 +160,13 @@ class ThreadSafeQueue * * This call blocks until a message is available. * - * \exception - * If the move constructor of the message throws, the exception is rethrown and the - * element remains in the queue. + *

Exception Safety

+ * If an exception occurs while moving the message, the exception is rethrown. The + * queue remains in a valid state, but it is unspecified whether the message was + * actually removed from the queue or not. If that is a concern, use the + * pop(MessageType&) overload instead. * - * \see try_pop() + * \see pop(MessageType&), try_pop() */ MessageType pop() { @@ -178,13 +180,39 @@ class ThreadSafeQueue return msg; } + /** + * Remove a message from the front of the queue and return it via an output parameter. + * + * This call blocks until a message is available. Its main advantage over the + * parameter-free pop() overload is better exception safety if the move assignment of + * the message can throw. If that is not the case, prefer pop() for improved + * readability. + * + *

Exception Safety

+ * If the move assignment of the message throws, the exception is rethrown. The + * element remains in the queue but its state depends on the guarantees of the message + * type. + * + * \see pop(), try_pop() + */ + void pop(MessageType& msg) + { + std::unique_lock lock{ mutex_ }; + cv_message_available_.wait(lock, [this] { return not queue_.empty(); }); + + msg = std::move(queue_.front()); + queue_.pop_front(); + lock.unlock(); + cv_slot_available_.notify_one(); + } + /** * Insert a message at the end of the queue. * * This call blocks until the queue has a free slot for the message. * - * \exception - * If the move or copy assignment of the message throws, the exception is rethrown + *

Exception Safety

+ * If the assignment of the message into the queue throws, the exception is rethrown * and no message is inserted. */ template Exception Safety + * If an exception occurs while moving the message, the exception is rethrown. The + * queue remains in a valid state, but it is unspecified whether the message was + * actually removed from the queue or not. If that is a concern, use the + * try_pop(MessageType&) overload instead. * - * \see pop() + * \see try_pop(MessageType&), pop() */ std::optional try_pop() { @@ -241,6 +271,36 @@ class ThreadSafeQueue return msg; } + /** + * If a message is available, remove it from the front of the queue and return it via + * an output parameter with a function return value of true; otherwise, return false. + * + * \param msg Output parameter to which the message is assigned if available; if the + * queue is empty, the value of this parameter is not changed. + * \returns true if a message was successfully removed from the queue and assigned to + * the output parameter; false if the queue was empty. + * + *

Exception Safety

+ * If an exception occurs while moving the message, that exception is rethrown. The + * message remains in the queue, but its value and the value of the output parameter + * depend on the guarantees of the message type. + * + * \see try_pop(MessageType&), pop() + */ + bool try_pop(MessageType& msg) + { + std::unique_lock lock{ mutex_ }; + + if (queue_.empty()) + return false; + + msg = std::move(queue_.front()); + queue_.pop_front(); + lock.unlock(); + cv_slot_available_.notify_one(); + return true; + } + /** * Try to insert a message at the end of the queue. * @@ -250,8 +310,8 @@ class ThreadSafeQueue * Messages given as an rvalue are only moved from if they can actually be inserted * into the queue. * - * \exception - * If the move or copy assignment of the message throws, the exception is rethrown + *

Exception Safety

+ * If the assignment of the message into the queue throws, the exception is rethrown * and no message is inserted. */ template Date: Wed, 28 Oct 2026 10:46:54 +0100 Subject: [PATCH 18/18] Add tests for new pop() and try_pop() overloads --- tests/test_ThreadSafeQueue.cc | 41 +++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/tests/test_ThreadSafeQueue.cc b/tests/test_ThreadSafeQueue.cc index a05aea60..82d6b32f 100644 --- a/tests/test_ThreadSafeQueue.cc +++ b/tests/test_ThreadSafeQueue.cc @@ -116,6 +116,25 @@ TEMPLATE_TEST_CASE("ThreadSafeQueue: pop() single-threaded", "[ThreadSafeQueue]" REQUIRE(queue.size() == 0); } +TEMPLATE_TEST_CASE("ThreadSafeQueue: pop(T&) single-threaded", "[ThreadSafeQueue]", int, + std::string, Message, std::unique_ptr) +{ + ThreadSafeQueue queue{ 10 }; + REQUIRE(queue.size() == 0); + + queue.push(TestType{}); + queue.push(TestType{}); + REQUIRE(queue.size() == 2u); + + TestType msg; + + queue.pop(msg); + REQUIRE(queue.size() == 1u); + + queue.pop(msg); + REQUIRE(queue.size() == 0); +} + TEST_CASE("ThreadSafeQueue: push() single-threaded", "[ThreadSafeQueue]") { ThreadSafeQueue queue{ 10 }; @@ -200,6 +219,28 @@ TEST_CASE("ThreadSafeQueue: try_pop() single-threaded", "[ThreadSafeQueue]") REQUIRE(queue.try_pop() == std::nullopt); } +TEST_CASE("ThreadSafeQueue: try_pop(T&) single-threaded", "[ThreadSafeQueue]") +{ + ThreadSafeQueue queue{ 2 }; + REQUIRE(queue.size() == 0); + + int msg{ 42 }; + REQUIRE(queue.try_pop(msg) == false); + REQUIRE(msg == 42); // value remains unchanged + + queue.push(1); + queue.push(2); + REQUIRE(queue.size() == 2u); + + REQUIRE(queue.try_pop(msg) == true); + REQUIRE(msg == 1); + + REQUIRE(queue.try_pop(msg) == true); + REQUIRE(msg == 2); + + REQUIRE(queue.try_pop() == std::nullopt); +} + TEST_CASE("ThreadSafeQueue: try_push() single-threaded", "[ThreadSafeQueue]") { ThreadSafeQueue queue{ 2 };