28. Threads and Lock-Free Queues

PySDR’s real-time GUI chapter runs the SDR in one thread and the plots in another, and its Detection chapter processes a continuous stream “in buffers”, one block at a time. As soon as a receiver does more than one thing at a time (read samples from the radio, filter them, decode them, draw them), it needs threads, and threads need a way to hand samples to each other.

In Python that hand-over is a queue.Queue, which takes a lock for every item. In a C++ receiver, the hand-over is the one piece of code that every sample passes through, and it sits between threads that run at real-time priority and threads that do not. It must never block the real-time side, it must not allocate, and it must be correct under the C++ memory model, which is harder than it looks. This chapter builds the standard tool for the job, a lock-free single-producer/single-consumer ring buffer, connects three threads with it, and shows how to find the bugs that tests do not find.

The Problem: Two Threads, One Buffer

Take two threads: a producer that writes blocks of samples (say, the thread that receives from the SDR) and a consumer that reads them (the DSP thread). Between them is a ring buffer with a write index (tail) and a read index (head). The producer writes samples into the free slots and then moves the tail; the consumer reads the slots between head and tail and then moves the head.

A std::mutex around both operations would be correct and simple, and for a GUI thread that is often fine. But a mutex is a problem on the real-time side: if the low-priority thread holds the lock and is pre-empted, the high-priority thread waits for it (priority inversion), and taking an uncontended lock can still involve the kernel. Ross Bencina’s rules for real-time audio, which we met in Appendix: Measuring Before Optimizing, put “no locks” right next to “no allocation” (Bencina 2011).

The key observation, going back to Lamport’s work on concurrent modules in 1983, is that with exactly one producer and one consumer, each index is written by only one thread. The producer writes only the tail, the consumer writes only the head. So no thread ever needs to modify a variable that another thread modifies too, and no lock or compare-and-swap loop is needed. What is needed is the right ordering of memory operations.

Acquire and Release

Consider the producer: it writes a sample into slot \(k\), then stores \(k+1\) into the tail. The consumer loads the tail, sees \(k+1\), and reads slot \(k\). Will it see the sample? Not necessarily. Without further instructions, the compiler and the CPU are allowed to reorder the two stores of the producer, or the two loads of the consumer, because within one thread the order does not matter. ARM processors, including the Apple M1 used here, do reorder memory accesses in practice; x86 processors reorder much less, which is why such bugs often appear only after porting to ARM.

C++11 gave us the words to say what we need (Williams, C++ Concurrency in Action, 2nd ed., chapter 5). A release store says: everything I wrote before this store is visible to any thread that sees this store. An acquire load says: if I see a value written by a release store, I also see everything that was written before it. The pair creates a synchronizes-with relation, and that is exactly the hand-over we need:

// producer
for (std::size_t i = 0; i < n; ++i) buf_[(tail + i) & (Capacity - 1)] = in[i];
tail_.store(tail + n, std::memory_order_release);   // samples above are visible before the new tail

// consumer
tail_cache_ = tail_.load(std::memory_order_acquire); // if I see the new tail ...
for (std::size_t i = 0; i < n; ++i) out[i] = buf_[(head + i) & (Capacity - 1)];  // ... I see the samples

The same pair, in the other direction, protects the head: the consumer releases the head after reading its slots, so the producer cannot overwrite a slot that is still being read. Each thread loads its own index with memory_order_relaxed, because no other thread writes it.

The Queue

Here is the core of spsc_ring (code/include/cppsdr/spsc.hpp). It moves whole blocks (std::span), because a receiver hands over blocks of samples, not single values, and it never blocks: push copies as many samples as fit and says how many.

template <class T, std::size_t Capacity>
class spsc_ring {
    static_assert(std::has_single_bit(Capacity), "capacity must be a power of two");
    static_assert(std::atomic<std::size_t>::is_always_lock_free);
public:
    std::size_t push(std::span<const T> in)
    {
        const std::size_t tail = tail_.load(std::memory_order_relaxed);   // only we write it
        if (Capacity - (tail - head_cache_) < in.size())                  // looks full: refresh
            head_cache_ = head_.load(std::memory_order_acquire);
        const std::size_t n = std::min(in.size(), Capacity - (tail - head_cache_));
        for (std::size_t i = 0; i < n; ++i) buf_[(tail + i) & (Capacity - 1)] = in[i];
        tail_.store(tail + n, std::memory_order_release);
        return n;
    }
    std::size_t pop(std::span<T> out);   // the mirror image
private:
    alignas(cache_line) std::atomic<std::size_t> tail_{0};  // written by the producer
    std::size_t head_cache_ = 0;                            // producer's copy of head_
    alignas(cache_line) std::atomic<std::size_t> head_{0};  // written by the consumer
    std::size_t tail_cache_ = 0;                            // consumer's copy of tail_
    alignas(cache_line) std::array<T, Capacity> buf_{};
};

Several small design decisions are worth a closer look:

  • The indices never wrap. They count up forever as std::size_t, and the slot is index & (Capacity - 1). The number of items is simply tail - head, which stays correct even when the counters overflow, because unsigned arithmetic is modular (the same property the integer NCO in Oscillators and Frequency Shifting relies on). There is no ambiguity between “full” and “empty”, and no slot is wasted. The static_assert makes sure the mask works.

  • Each thread caches the other’s index. Reading the other thread’s index means fetching a cache line that the other core keeps modifying. The producer only re-reads the head when its cached copy says the queue looks full, and vice versa; most calls touch only memory the calling thread owns. Erik Rigtorp describes this optimization in “Optimizing a ring buffer for throughput”, and his widely used SPSCQueue implements it.

  • No false sharing. If the producer’s and the consumer’s index shared a cache line, every write by one would evict the line from the other’s cache, even though they never touch the same variable. alignas(std::hardware_destructive_interference_size) (C++17) puts each index, together with the cached copy used by the same thread, on its own cache line (Williams, chapter 8).

  • It is lock-free, and we check that. std::atomic<T> may fall back to a hidden lock for types the hardware cannot handle atomically; is_always_lock_free asserts at compile time that it does not.

Sleeping Without Locks

A real-time thread must never wait on a queue: if there is no data, it does something else or reports an underrun. But the threads around it (a file writer, a decoder, a GUI) should sleep while there is nothing to do, rather than spin and burn a core. Before C++20 that required a mutex and a condition variable next to the lock-free queue. C++20 added wait and notify_one directly to std::atomic:

// consumer side, a thread that may sleep
const std::size_t seen = q.tail();
const std::size_t n = q.pop(block);
if (n == 0) q.wait_for_data(seen);   // tail_.wait(seen): sleep until the tail changes

// producer side
q.push(block);
q.notify_consumer();                 // tail_.notify_one()

tail_.wait(seen) returns only once the tail differs from seen, so there is no lost wake-up: if the producer pushed between our tail() and wait(), the value has already changed and wait returns immediately. Note one property that trips people up: a notify_one without a change of the value does not end a wait, which re-checks the value and goes back to sleep. So you cannot use it to wake a thread for shutdown without changing something it watches.

A Pipeline on Three Threads

code/tests/test_spsc.cpp builds the smallest interesting receiver: a source thread that pushes blocks of random size (as a radio driver would), a DSP thread that frequency-shifts with the integer NCO and low-pass filters with the compile-time fir_static, and the main thread as the sink, connected by two queues of 4096 samples:

spsc_ring<cf32, 4096> q1, q2;
{
    std::jthread source([&] { /* push_all(q1, next block) ... */ });
    std::jthread dsp([&] {
        dsp_stage d;                       // NCO + FIR, state lives in this thread only
        std::vector<cf32> in(1024), out(1024);
        for (std::size_t done = 0; done < total;) {
            const std::size_t seen = q1.tail();
            const std::size_t n = q1.pop(std::span(in));
            if (n == 0) { q1.wait_for_data(seen); continue; }
            q1.notify_producer();
            d.process(std::span(in).first(n), std::span(out).first(n));
            push_all(q2, std::span<const cf32>(out).first(n));
            done += n;
        }
    });
    // ... the main thread pops q2 into the output
}   // std::jthread joins in its destructor

Two million samples go through, and the output is compared with the same NCO and filter run on the whole signal in a single thread: identical, bit for bit. The DSP objects keep their state across the irregular blocks, as they were designed to.

std::jthread (C++20) is std::thread with two improvements: it joins automatically in its destructor (a std::thread that is destroyed while still joinable calls std::terminate, a classic exception-safety bug that Williams discusses at length), and it carries a std::stop_token for cooperative cancellation. Because the queues and vectors are declared before the scope with the threads, the threads are joined before the data they use is destroyed; the scope makes the lifetime rule visible.

Finding the Bugs Tests Do Not Find

How do we know the memory orders are right? Not by testing alone. The queue template has a parameter for the publishing order, so that we can build it wrong on purpose, with memory_order_relaxed instead of release and acquire (code/demos/spsc_race_demo.cpp), and push 100 000 numbers through it, summing them on the other side. Built normally and run ten times on the M1, it printed the correct sum nine times and once a wrong one; run fifty more times, it was right every time. That is the nature of this kind of bug: it depends on timing, it is rare, and a test suite that passes proves almost nothing (Williams makes exactly this point in chapter 11).

ThreadSanitizer takes a different approach. It does not wait for an unlucky interleaving; it tracks the happens-before relations of every memory access and reports any pair of accesses from different threads that is not ordered, on every run. Built with -fsanitize=thread, the broken queue is reported immediately:

WARNING: ThreadSanitizer: data race (pid=58952)
  Read of size 4 at 0x00016f019900 by main thread:
    #0 main spsc.hpp
  Previous write of size 4 at 0x00016f019900 by thread T1:
    #0 cppsdr::spsc_ring<int, 1024ul, (std::__1::memory_order)0>::push(...) spsc.hpp:45

Line 45 is the producer’s write into the buffer, and the read is the consumer’s: exactly the hand-over that release and acquire are supposed to order. (In this sanitized run the sum was also wrong, by exactly 1024: the consumer read a slot one lap of the ring too early.) The CMake build compiles the pipeline test a second time with ThreadSanitizer (test_spsc_tsan), so every test run checks the correct queue for races as well; it reports none.

Where This Fits

GNU Radio’s scheduler runs one thread per block and connects them with buffers that have one writer and possibly several readers, the doubly mapped buffers from FIR Filters in C++ (buffer_double_mapped), with the same discipline: each reader owns its read index, the writer owns the write index. The pattern in Pirkle’s Designing Audio Effect Plugins in C++ (2nd ed., chapter 21) for drawing waveforms and spectra is the same queue from the other side: the audio thread pushes, the GUI thread pops on a timer and never makes the audio thread wait. For more producers or consumers, the problem changes character completely (compare-and-swap loops, the ABA problem, memory reclamation; Williams chapter 7 and Pikus chapter 7), and the honest first answer is usually a mutex, measured, before anything lock-free.

Key Takeaways

  • With one producer and one consumer, each index has one writer, and a ring buffer needs no locks, only release stores and acquire loads.

  • Let indices count up and mask them; unsigned wrap-around keeps tail - head correct forever.

  • Keep each thread’s data on its own cache line (std::hardware_destructive_interference_size) and cache the other thread’s index.

  • The real-time thread never waits; other threads sleep with C++20 std::atomic::wait/notify_one instead of spinning.

  • std::jthread joins automatically; declare shared data before the threads that use it.

  • Memory-ordering bugs are rare and timing-dependent. Run your threaded tests under ThreadSanitizer, always.