Member-only story

Modern C++: Writing a thread-safe Queue

Marco Massenzio
6 min readJul 26, 2020

--

The STL provides a high-performance queue class in std::queue<T>; however, the API is not very intuitive, or easy, to use and it is not safe to access from multiple threads.
In this article, we will show how to wrap it in a more convenient, and thread-safe, API.

The C++ Standard Template Library (STL) offers a template-class std::queue<T> that implements Queue semantics: the usual push/ pop/ empty methods to implement a FIFO queue for elements of type T.

The class also offers the ability to specify the underlying Container to use for storage at construction ( is used by default).

The requirements on the T class of queued elements are pretty light, the most obvious being that they must be "copyable" (although, if the class to be contained cannot be copied, one can use either references of pointers - with the usual caveat that it becomes a bit trickier to ensure they don't go out of scope while still being referenced to from the queue).

The design (and implementation) of the API is meant for performance and small memory footprint; however, it makes for a somewhat awkward usage; most surprising is that pop() will not return the T element at the front of the queue, if any.

One has to use front() to actually get it, then pop() to remove; further, if there is no such element…

--

--

No responses yet

Write a response