Skip to content
LeetQuant
QD06 Concurrency and Networking

QD06 · Concurrency and Networking · Lesson 3 of 5

Lock-Free Queues

A single-producer single-consumer ring buffer with acquire/release indices, implemented and tested across two threads, padding against false sharing with a measured effect, and why multi-producer multi-consumer queues are much harder.

17 min

Why SPSC is the workhorse

A trading system is usually a pipeline of pinned threads: feed handler, then strategy, then order gateway, each on its own core. Between each pair sits a queue with exactly one writer and one reader. That restriction is what makes a fast, simple, provably correct lock-free queue possible:

  • The producer is the only thread that writes head; the consumer is the only thread that writes tail. No index ever needs a CAS.
  • Each side only needs to read the other side's index, and acquire/release on those two variables is enough to hand over the slot contents.
  • Nothing is ever freed or reused out of order, so there is no ABA problem.

No thread ever blocks in the kernel; a full or empty queue just returns false and the caller decides whether to spin, drop or back off. The queue has fixed capacity, so there is no allocation on the hot path.

Design

Use free-running unsigned indices that only increase, and map them to slots with index & (N - 1), so NN must be a power of two. Then

size=head−tail,empty  ⟺  head=tail,full  ⟺  head−tail=N.\text{size} = \text{head} - \text{tail}, \qquad \text{empty} \iff \text{head} = \text{tail}, \qquad \text{full} \iff \text{head} - \text{tail} = N.

Unsigned subtraction wraps modulo 2642^{64}, and because NN divides 2642^{64} the difference is still correct after the indices overflow. (Free-running indices also avoid the classic "is head == tail empty or full?" ambiguity that forces wrap-around designs to waste a slot.)

The ordering argument has two halves:

  1. Producer writes the slot, then head.store(h + 1, release). Consumer does head.load(acquire), then reads the slot. If the consumer sees the new head, the slot write happens before its read.
  2. Consumer reads the slot, then tail.store(t + 1, release). Producer does tail.load(acquire) before overwriting that slot. The consumer has finished reading before the producer reuses it.

Each thread loads its own index with relaxed, since no other thread writes it. A useful refinement is to cache the other side's index: the producer keeps a private copy of tail and only reloads the shared one when the queue looks full. That turns most operations into touches of the thread's own cache lines only.

Worked example

implement and test the SPSC ring buffer

Implement SpscQueue<T, N> with try_push and try_pop. Test it with one producer pushing 1,…,1071, \dots, 10^7 and one consumer popping them, checking order and the sum.

Show solution
#include <atomic>
#include <chrono>
#include <cstddef>
#include <iostream>
#include <optional>
#include <thread>

// Single-producer single-consumer ring buffer. N must be a power of two.
template <typename T, std::size_t N>
class SpscQueue {
    static_assert(N >= 2 && (N & (N - 1)) == 0, "N must be a power of two");
public:
    bool try_push(const T& v) {                                  // producer thread only
        const std::size_t h = head_.load(std::memory_order_relaxed);
        if (h - tail_cache_ == N) {                              // looks full: refresh the cache
            tail_cache_ = tail_.load(std::memory_order_acquire);
            if (h - tail_cache_ == N) return false;              // really full
        }
        buf_[h & (N - 1)] = v;                                   // write the slot...
        head_.store(h + 1, std::memory_order_release);           // ...then publish it
        return true;
    }
    std::optional<T> try_pop() {                                 // consumer thread only
        const std::size_t t = tail_.load(std::memory_order_relaxed);
        if (t == head_cache_) {                                  // looks empty: refresh the cache
            head_cache_ = head_.load(std::memory_order_acquire);
            if (t == head_cache_) return std::nullopt;           // really empty
        }
        T v = buf_[t & (N - 1)];                                 // read the slot...
        tail_.store(t + 1, std::memory_order_release);           // ...then hand it back
        return v;
    }
private:
    static constexpr std::size_t kLine = 64;                     // cache-line size on x86 and most ARM
    alignas(kLine) std::atomic<std::size_t> head_{0};            // written by producer
    alignas(kLine) std::size_t tail_cache_ = 0;                  // producer's copy of tail
    alignas(kLine) std::atomic<std::size_t> tail_{0};            // written by consumer
    alignas(kLine) std::size_t head_cache_ = 0;                  // consumer's copy of head
    alignas(kLine) T buf_[N];
};

int main() {
    constexpr long kCount = 10'000'000;
    static SpscQueue<long, 1024> q;
    long sum = 0, expected_next = 1;
    bool in_order = true;

    auto start = std::chrono::steady_clock::now();
    std::thread consumer([&] {
        for (long got = 0; got < kCount;) {
            if (auto v = q.try_pop()) {
                if (*v != expected_next++) in_order = false;
                sum += *v;
                ++got;
            }
        }
    });
    std::thread producer([&] {
        for (long i = 1; i <= kCount; ++i)
            while (!q.try_push(i)) {}                            // spin while full
    });
    producer.join();
    consumer.join();
    double secs = std::chrono::duration<double>(std::chrono::steady_clock::now() - start).count();

    std::cout << "sum = " << sum << " (expected " << kCount * (kCount + 1) / 2 << ")\n"
              << "in order: " << std::boolalpha << in_order << '\n'
              << "throughput: " << static_cast<long>(kCount / secs / 1e6) << " M items/s\n";
}

Output on an Apple M1 (three runs gave 19, 20 and 18 M items/s):

sum = 50000005000000 (expected 50000005000000)
in order: true
throughput: 19 M items/s

107(107+1)2=50,000,005,000,000\frac{10^7(10^7 + 1)}{2} = 50{,}000{,}005{,}000{,}000, so every item arrived exactly once and in FIFO order.

Things to point out: tail_cache_ is touched only by the producer and head_cache_ only by the consumer, so they are plain variables. The queue is static because the 8 KB buffer plus padding is better off the stack. A queue test should also run under ThreadSanitizer (-fsanitize=thread) on a platform where it is supported, since a passing sum does not prove the absence of races.

Be honest about the benchmark. A mutex-plus-condition-variable queue moving the same 10 million items took about 0.48 s on this machine, a similar throughput, because every item crosses between cores either way and the cache-line transfer dominates. The SPSC queue's advantages are elsewhere: no syscalls, no thread ever sleeping, no allocation, bounded memory, and therefore far tighter tail latency. Real systems widen the gap further by moving batches per index update.

False sharing

Caches move memory in lines (64 bytes on x86; Apple's M-series reports 128 bytes). Coherence works per line: when one core writes, every other core's copy of that line is invalidated. If the producer's head and the consumer's tail share a line, each write by one thread evicts the line from the other thread's cache even though they never touch the same variable. This is false sharing.

A direct measurement: two threads each do 50 million relaxed fetch_adds on their own counter, first with both counters in one struct, then with alignas(64) on each.

#include <atomic>
#include <chrono>
#include <iostream>
#include <thread>

struct Packed { std::atomic<long> a{0}; std::atomic<long> b{0}; };                          // same cache line
struct Padded { alignas(64) std::atomic<long> a{0}; alignas(64) std::atomic<long> b{0}; };  // separate lines

template <typename S>
double time_it() {
    S s;
    auto start = std::chrono::steady_clock::now();
    std::thread t1([&] { for (int i = 0; i < 50'000'000; ++i) s.a.fetch_add(1, std::memory_order_relaxed); });
    std::thread t2([&] { for (int i = 0; i < 50'000'000; ++i) s.b.fetch_add(1, std::memory_order_relaxed); });
    t1.join();
    t2.join();
    return std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - start).count();
}

int main() {
    std::cout << "same line:      " << static_cast<int>(time_it<Packed>()) << " ms\n";
    std::cout << "separate lines: " << static_cast<int>(time_it<Padded>()) << " ms\n";
}
same line:      500 ms      499 ms      506 ms
separate lines: 203 ms      142 ms      148 ms

The threads share no data, yet sharing a line made them 2.5 to 3.5 times slower. That is why the queue above puts each index, each cached copy and the buffer on its own line. C++17 offers std::hardware_destructive_interference_size for the padding; note that on this M1 it reports 64 while the OS reports a 128-byte line, so latency-critical code often pads to 128 to be safe on both families.

Why MPMC is much harder

With several producers, writing a slot and advancing head are no longer owned by one thread:

  • Claiming a slot needs an RMW. Producers must fetch_add or CAS on a shared head, so that line bounces between all producers on every push.
  • Claiming and publishing separate. Producer 1 claims slot 5 and producer 2 claims slot 6; if producer 2 finishes first, the consumer must not read slot 5 yet. A single head can no longer mean "everything below me is ready". The standard fix (Dmitry Vyukov's bounded MPMC queue) gives each slot its own sequence number that says whether it is empty or full for a given lap.
  • Progress. A producer pre-empted between claiming and publishing stalls every consumer behind its slot. The queue is lock-free in name but can still wait on a sleeping thread.
  • Unbounded, linked versions (Michael–Scott queue) add ABA and memory reclamation problems on top.

The engineering answer is usually to avoid MPMC: give each producer its own SPSC queue and let the consumer poll them in turn, or route by symbol so each queue has one writer.

Knowledge check

In try_push, why does the producer publish with head_.store(h + 1, release) rather than relaxed?

Knowledge check

The producer loads its own head_ with memory_order_relaxed. Why is that safe?

Knowledge check

Two threads each update their own counter, but the counters are adjacent fields of one struct, and the program runs about three times slower than expected. What is the likely cause and fix?

Key takeaways

  • SPSC works because each index has exactly one writer: no CAS, no ABA, only acquire/release pairs on head and tail.
  • Free-running indices with a power-of-two capacity give size = head - tail without wasting a slot, even across overflow.
  • Write the slot, then release the index; acquire the index, then read the slot.
  • Cache the other side's index and pad each hot variable to its own cache line; false sharing alone cost about 3x in the demo.
  • The win is predictable latency (no syscalls, no sleeping, no allocation), not necessarily raw throughput.
  • MPMC needs RMWs to claim slots and per-slot sequence numbers to publish; prefer several SPSC queues.

Finished reading?

Answer the 3 knowledge checks to complete this lesson (0 done).