atomic_queue
C++14 multiple-producer-multiple-consumer lock-free queues based on ring-buffers and std::atomic.
Designed with a goal to minimize the latency between one thread pushing an element into a queue and another thread popping it from the queue.
It has been developed, tested and benchmarked on Linux x86_64. Yet, any C++14 platform implementing std::atomic is expected to compile the unit-tests and run them without failures just as well.
Continuous Integrations
GitHub Actions run continuous integrations unit-tests on the following platforms:
Pull requests to extend the continuous integrations to run on other architectures/platforms are most welcome.
Design Principles
When minimizing latency a good design is not when there is nothing left to add, but rather when there is nothing left to remove, as these queues exemplify.
Minimizing latency naturally maximizes throughput. Low latency reciprocal is high throughput, in ideal mathematical and practical engineering sense. Low latency is incompatible with any delays and/or batching, which destroy original (hardware) global time order of events pushed into one queue by different threads. Maximizing throughput, on the other hand, can be done at expense of latency by delaying and batching multiple updates.
The main design principle these queues follow is minimalism, which results in such design choices as:
- Bare minimum of atomic instructions. Inlinable by default push and pop functions can hardly be any cheaper in terms of CPU instruction number / L1i cache pressure.
- Explicit contention/false-sharing avoidance for queue data members and its elements.
- Linear fixed capacity ring-buffer array. No heap memory allocations after a queue object has constructed. It doesn't get any more CPU L1d or TLB cache friendly than that.
- Value semantics. Meaning that the queues make a copy/move upon
push/pop and keep no references/pointers to its function arguments after returning, and that no reference/pointer to elements in the queue ring-buffer can be obtained. Simplest to use, hard to misuse, best machine code due to no pointer aliasing possible.
The impact of each of these small design choices on their own is barely measurable, but their total impact is much greater than a simple sum of the constituents' impacts, aka super-scalar compounding or synergy. The synergy emerging from combining multiple of these small design choices together is what allows CPUs to perform at their peak capacities least impeded.
These design choices are also limitations:
- The maximum queue size must be set at compile time or construction time. The ring-buffer side-steps the memory reclamation problem inherent in linked-list based queues for the price of fixed buffer size. See Effective memory reclamation for lock-free data structures in C++ for more details. Fixed buffer size may not be that much of a limitation, since once the queue gets larger than the maximum expected size that indicates a problem that elements aren't consumed fast enough, and if the queue keeps growing it may eventually consume all available memory which may affect the entire system, rather than the problematic process only. The only apparent inconvenience is that one has to do an upfront calculation on what would be the largest expected/acceptable number of unconsumed elements in the queue.
- There are no OS-blocking push/pop functions. This queue is designed for ultra-low-latency scenarios and using an OS blocking primitive would be sacrificing push-to-pop latency. For lowest possible latency one cannot afford calling the OS kernel or blocking in the OS kernel because the wake-up latency of a blocked thread is about 1-3 microseconds, whereas this queue's round-trip time (push a message to another thread and pop its reply) can be below 100 nanoseconds. CPU vulnerability mitigations made system calls dramatically more expensive, crippling performance even worse. In general, handing off spin-waiting to an OS blocking primitive is a problem with no satisfactory low-latency solutions.
Ultra-low-latency applications need just that and nothing more. The minimalism pays off, see the throughput and latency benchmarks.
Common Use-Cases
These queues fit any scenario where threads hand off small, copyable/movable messages and the number of in-flight elements has a sensible upper bound. Some typical uses:
- Low-latency messaging hot paths. Passing market data updates, orders, or events between threads/processes in trading and other latency-sensitive systems, where the sub-100ns push-to-pop latency and preserved global time order matter.
- Logging and telemetry offload. Handing log records or metrics off the hot path to a background thread that does the formatting and I/O, keeping the latency-critical thread free of syscalls and allocations.
- Inter-process communication via shared memory. Non-
B variants are position-independent fixed-capacity queues with no heap allocations and no internal pointers/references, designed to be constructed in a shared-memory segment (e.g. mmap/shm_open) and used to pass trivially-copyable messages between separate processes lock-free. Use a trivially-copyable element type for the best results.
- Producer/consumer pipelines. Decoupling a fast producer from a slower consumer (or vice versa) using a bounded/fixed-capacity buffer that applies natural back-pressure:
try_push failure signals the consumer can't keep up, rather than letting the queue grow unbounded and exhaust memory.
- Work/task distribution. Fanning out units of work from one or more producers to a pool of worker threads (MPMC), or feeding a single dedicated worker (MPSC/SPSC).
- SPSC channels. A single-producer/single-consumer queue between two threads (e.g. a network I/O thread feeding a processing thread) using the SPSC-tuned configuration for the lowest overhead.
- Passing ownership across threads. The
2 variants store non-atomic element types such as std::unique_ptr, allowing ownership of heap objects to be transferred between threads through the queue.
- Object/index pools. Recycling reusable objects, buffer slots, or free-list indices between threads by pushing/popping small integer handles.
These queues are a poor fit when you need unbounded capacity, OS-level blocking (condition-variable-style waiting) instead of spin-waiting, per-element priorities, or when elements are large enough that copying/moving them on push/pop dominates -- in those cases prefer a different data structure.
Role Models
Several other well established and popular thread-safe containers are used for reference in the benchmarks:
| Queue |
Type |
Description |
std::mutex |
MPMC |
A fixed capacity ring-buffer with std::mutex. |
pthread_spinlock |
MPMC |
A fixed capacity ring-buffer with pthread_spinlock_t. |
boost::lockfree::spsc_queue |
SPSC |
A wait-free queue from Boost library. |
boost::lockfree::queue |
MPMC |
A lock-free queue from Boost library. |
moodycamel::ConcurrentQueue |
quasi-MPMC |
A lock-free queue used in non-blocking mode. Designed to maximize throughput at the expense of latency, eschewing global time order, by emulating a MPMC queue with a bunch of SPSC queues under the hood. It is not equivalent to other queues benchmarked here in this respect. |
moodycamel::ReaderWriterQueue |
SPSC |
A lock-free queue used in non-blocking mode. |
xenium::michael_scott_queue |
MPMC |
A lock-free queue proposed by Michael and Scott (similar to boost::lockfree::queue which is also based on the same proposal). |
xenium::ramalhete_queue |
MPMC |
A lock-free queue proposed by Ramalhete and Correia. |
xenium::vyukov_bounded_queue |
MPMC |
A bounded queue based on the version proposed by Vyukov. |
tbb::spin_mutex |
MPMC |
A locked fixed capacity ring-buffer with tbb::spin_mutex from Intel Threading Building Blocks. |
tbb::concurrent_bounded_queue |
MPMC |
Eponymous queue used in non-blocking mode from Intel Threading Building Blocks. |
Library contents
Available queues
AtomicQueue - a fixed capacity ring-buffer for atomic elements.
OptimistAtomicQueue - a faster fixed capacity ring-buffer for atomic elements which busy-waits when empty or full. It is AtomicQueue used with push/pop instead of try_push/try_pop.
AtomicQueue2 - a fixed capacity ring-buffer for non-atomic elements.
OptimistAtomicQueue2 - a faster fixed capacity ring-buffer for non-atomic elements which busy-waits when empty or full. It is AtomicQueue2 used with push/pop instead of try_push/try_pop.
These containers maintain their ring-buffers as array data members with size specified at compile-time and have no pointer data members. That makes them position-independent, allows allocating them into process-shared memory with a plain C++ placement new statement, and mapping at arbitrary addresses in different processes using the same queue objects in shared memory. The queue elements must be position-independent too to support this particular use-case (unlike classes with process-position-dependent pointers such as std::unique_ptr, std::string and all the C++ standard containers with default allocators).
There are corresponding B variants (AtomicQueueB, OptimistAtomicQueueB, AtomicQueueB2, OptimistAtomicQueueB2) that use std::allocator or user-specified (stateful) allocator for allocating the ring-buffers, where the buffer size is specified as an argument to the constructor at run-time.
Totally ordered mode is supported. In this mode consumers receive messages in the same FIFO order the messages were posted. This mode is supported for push and pop functions, but not for the try_ versions. On Intel x86 the totally ordered mode has 0 cost, as of 2019.
Single-producer-single-consumer mode is supported. In this mode, no expensive atomic read-modify-write CPU instructions are necessary, only the cheapest atomic loads and stores. That improves queue throughput significantly.
Move-only queue element types are fully supported. For example, a queue of std::unique_ptr<T> elements would be AtomicQueueB2<std::unique_ptr<T>> or AtomicQueue2<std::unique_ptr<T>, CAPACITY>.
Queue Schematics
[oldest-element, ..., newest-element]
[queue-front , ..., queue-back]
[Queue.beg_ , ..., Queue.end_)
Queue.pop Queue.push
Queue Types
The ring-buffer can be stored as an array data member (capacity fixed at compile-time) or on the heap (allocated via an allocator, capacity specified at run-time). The element type can be atomic or non-atomic