Skip to content

Thread-safe queue - #61

Open
alt-graph wants to merge 19 commits into
mainfrom
feature/ThreadSafeQueue
Open

alt-graph wants to merge 19 commits into
mainfrom
feature/ThreadSafeQueue

Conversation

@alt-graph

Copy link
Copy Markdown
Member

This is a port of the LockedQueue from Taskolib. This has already spread via copy&paste to several projects, so it might be good to standardize it. I looked at it and already found some things to improve, especially regarding exception safety and the notification scheme. We might also think about extending it with more features like automatic termination, but for me it would already be good as-is.

Regarding the license: I got approval from Marcus to re-license this to MIT; all other authors are present here as well.

[why]
No good reason, except that this follows our style guide and it makes
the code bases more consistent.
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.
[why]
Marcus is one of the original authors of Taskolib's LockedQueue.
[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.
[why]
A queue with zero entries does not make sense.

[how]
Throw std::invalid_argument when constructing ThreadSafeQueue{ 0 }.
[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).
[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.
[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.
[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.
[why]
What we constructed before by moving from the queue was a T, not an
optional<T>. This made it somewhat inefficient to return it from the
function.

[how]
Directly construct an optional<T> from the moved queue element. This is
then a candidate for NRVO.
[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.
@Finii

Finii commented Oct 27, 2026 •

Copy link
Copy Markdown
Member

This looks good, will have a look later.

The only thing that comes to my mind after skimming the docs: It does not specify much about the setup, so I assume it can handle n producers and m consumers.

I'm not so sure that that n:m constellation is often the case in doocs server contexts.

For 1:1 contexts we could also add a lock free version (or not, I do not really care):

// A producer consumer design pattern
// fifo aehm queue
//
// - Lock free
// - Thread save (for 1 writer / 1 reader situations)
// - Can fail if queue is empty (on pop) or full (on push) (see *)
//
// Design idea taken from vanDooren's MSMVPs blog 5. Jan 2007
// Mixed in with Dr.Dobbs 'Writing Lock-Free Code' 29. Sep 2008
//
// It needs one element more storage than having usable elements
//
// *) This is of no concern because in this server the producer
// will add single entries much more often that the consumer checks
// for entries. But then the consumer will consume all available
// entries at once.
//
// July 2017, Fini Jastrow

#pragma once
#include <atomic>

template<typename ELEMENT_T, std::size_t SIZE>
struct LockFreeQueue {

https://mcs-gitlab.desy.de/controls-and-operation/utility/correlator/-/blob/main/LockFreeQueue.hh

I found that I have virtually zero use cases where n or m is not 1.

@Finii

Finii commented Oct 27, 2026

Copy link
Copy Markdown
Member

LLMs 🤪

image

@Finii

Finii commented Oct 27, 2026

Copy link
Copy Markdown
Member

Note to self: Of course not MIT, but nevertheless: https://github.com/cameron314/concurrentqueue

@alt-graph

Copy link
Copy Markdown
Member Author

This looks good, will have a look later.

The only thing that comes to my mind after skimming the docs: It does not specify much about the setup, so I assume it can handle n producers and m consumers.

I'm not so sure that that n:m constellation is often the case in doocs server contexts.

For 1:1 contexts we could also add a lock free version (or not, I do not really care):

// A producer consumer design pattern
// fifo aehm queue
//
// - Lock free
// - Thread save (for 1 writer / 1 reader situations)
// - Can fail if queue is empty (on pop) or full (on push) (see *)
//
// Design idea taken from vanDooren's MSMVPs blog 5. Jan 2007
// Mixed in with Dr.Dobbs 'Writing Lock-Free Code' 29. Sep 2008
//
// It needs one element more storage than having usable elements
//
// *) This is of no concern because in this server the producer
// will add single entries much more often that the consumer checks
// for entries. But then the consumer will consume all available
// entries at once.
//
// July 2017, Fini Jastrow

#pragma once
#include <atomic>

template<typename ELEMENT_T, std::size_t SIZE>
struct LockFreeQueue {

https://mcs-gitlab.desy.de/controls-and-operation/utility/correlator/-/blob/main/LockFreeQueue.hh

I found that I have virtually zero use cases where n or m is not 1.

Explaining the design and use case a bit better in the explanation is a very good idea. To my understanding the queue is capable of handling N producers and M consumers, but it would not scale well if either N or M are big. I'll add a commit to improve the docs.

Regarding a LockFreeQueue: Generally speaking that could come in handy as well, although I also do not have any immediate use cases where we cannot afford a mutex.

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.
[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.
[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.
@alt-graph

Copy link
Copy Markdown
Member Author

Hi everyone,
I guess this ThreadSafeQueue is ready to review now. Please comment on the new void overloads for pop() and try_pop(); IMO they are ugly and probably not necessary.

@Finii Finii left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have questions about the capacity.

A thread-safe queue with fixed maximum capacity for [...]

Also

        if (capacity == 0)
        {
            throw std::invalid_argument(
                "ThreadSafeQueue capacity must be greater than 0");
        }
  1. Why is ThreadSafeQueue fixed-size and does not use the underlying SlidingBuffer's fixed-size version (but the dynamic size version)? Or otoh, why is ThreadSafeQuere not dynamic in size? I would expect either it being fixed size and then using a fixed size container, or using a dynamic size container and then handing out the resizability to its own users.
  2. Why does it hard-fail on an empty size? Is there a bug in SlidingBuffer or would that require some very special handling? Usually it should be fine by SlidingBuffer. Of course it might seem useless, but it is not our concern if a user wants a container with zero space. As std::array also allows size zero and is not resizable.

return true;
}

private:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
private:
protected:

to facilitate development/improvements/customization.

Comment thread include/gul17/ThreadSafeQueue.h Resolved
Comment thread include/gul17/ThreadSafeQueue.h Resolved
*
* 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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not really sure what back() is for.
And if we have a back(), why not a try_back().

This seems to be tailored to some obscure use-case.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not so obscure... sometimes you want to examine the last element without taking it out of the queue. But a try_back() might indeed make sense.

static_assert(std::is_move_constructible_v<MessageT>,
"Message type must be move-constructible");
static_assert(
std::is_move_assignable_v<MessageT>, "Message type must be move-assignable");

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this true? Wouldn't a copyable type also work?
I am a bit confused about which condition contains what.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well, normal copy-constructible types are also implicitly move-constructible. But if you make your own type and delete the move constructor/assignment, it won't work with this class, so I'd say the condition is correct.

* \note
* Obviously, this function requires the message to be copyable.
*/
MessageType back() const

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we have back, why not also operator[]() and at()? That would cost us almost nothing and allow more use-cases where the quere should be examined by the consumer in some way etc (which is probably the reason for back()).

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am not sure how one would use at(), let alone [], for a thread-safe queue because its size can change at any time. Sure, we could implement that, but if you can't even write a safe for loop, what is the point?

It is true that back() is essentially something like at(size()-1), but it bundles that into an atomic operation and waits for an element to come in.

@Finii

Finii commented Dec 1, 2026 •

Copy link
Copy Markdown
Member

Please comment on the new void overloads for pop() and try_pop(); IMO they are ugly and probably not necessary.

Well, I would not call them ugly, but that is a bit old fashioned. I feel the same, maybe remove.

Edit: Feels like out-via-pointer C code. Only updated to reference instead of pointer. Output should be via return value except when there a very special requirements/conditions imho.

@alt-graph

Copy link
Copy Markdown
Member Author

Let me start with this point:

2. Why does it hard-fail on an empty size? Is there a bug in SlidingBuffer or would that require some very special handling? Usually it should be fine by SlidingBuffer. Of course it might seem useless, but it is not our concern if a user wants a container with zero space. As std::array also allows size zero and is not resizable.

I guess allowing zero capacity would require special handling for that case: push() and try_push() would need an additional check for the condition variable because a zero-capacity SlidingBuffer is by definition always filled(). Same for pop() and back(): They would wait indefinitely in the current implementation.

So yes, we could make zero capacity work, but it does not come natural for this container.

@alt-graph

Copy link
Copy Markdown
Member Author
  1. Why is ThreadSafeQueue fixed-size and does not use the underlying SlidingBuffer's fixed-size version (but the dynamic size version)? Or otoh, why is ThreadSafeQuere not dynamic in size? I would expect either it being fixed size and then using a fixed size container, or using a dynamic size container and then handing out the resizability to its own users.

Good question. I honestly see few concrete use cases for making the queue resizable, but someone will certainly come up with one. So I guess we should make it resizable, right?

@Finii

Finii commented Dec 2, 2026

Copy link
Copy Markdown
Member

Good question. I honestly see few concrete use cases for making the queue resizable, but someone will certainly come up with one. So I guess we should make it resizable, right?

Well a use case is a command buffer, and in a server you can (dynamically) increase the buffer depth.
But then, yes, 'few' examples, and maybe not worth it.
Otoh, at least in my mind it just exposes the resizing functions from underlying and adds

  • restriction to shrink only empty slots
  • probably signal the slot-empty-CV (after expansion)

But ... I would also be fine with a fixed size Queue, but that should use the fixed size underlying imho.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants