
Recall first from Atomic reference counting
- A reference count turns 'who deletes this?' into an atomic read-modify-write, so no mutex is needed and threads never sleep on ownership
- fetch_sub returns the previous value; the thread that sees 1 was the last owner and must delete
- Increments can be relaxed, but the decrement needs release and the final zero path needs acquire, commonly one acq_rel fetch_sub
One writer per index: the SPSC ring buffer
3 min readThe previous lesson counted owners with atomic increments. This lesson designs a single-producer single-consumer ring buffer where no lock is taken, stress-tests it, benchmarks it against a mutex queue, and looks at false sharing and MPMC designs.
Two-thread pipelines are everywhere in embedded Linux: one thread reads samples from a device file or socket, a second thread filters, logs, or forwards them. The obvious queue is a std::deque guarded by a std::mutex, and it works. But a contended mutex on Linux can enter the kernel through the futex system call to sleep and be woken again, which adds syscalls and scheduler latency to precisely the handoff you want to keep cheap and predictable. When the topology is fixed at one pusher and one popper, there is a cheaper structure.
A a queue with exactly one single producer thread and one single consumer thread, a restriction that removes all write/write contention can be a ring buffer: a fixed array of N slots plus two indices, head (the next slot to pop) and tail (the next slot to push), both wrapping back to zero at the end of the array. The design rests on one ownership rule: the producer is the only thread that ever writes tail, and the consumer is the only thread that ever writes head. Both threads may read both indices. Because no variable ever has two writers, no compare-and-swap is needed anywhere: the CAS loops from the earlier lesson exist to arbitrate between competing writers, and here there is no competition. Each push and pop finishes in a bounded number of its own steps and can never be delayed by another thread holding a lock (the operations are even wait-free, the strongest progress guarantee, though a consumer that spins waiting for items still waits for the producer), which is the strongest form of the progress guarantee that no thread can block another by holding a lock; some thread always makes progress in a finite number of steps guarantee.
Two details make the indices usable. First, empty and full must be distinguishable: head == tail means empty, but if the producer were allowed to fill the last free slot, full would also give head == tail. The classic fix reserves one slot: usable capacity is N - 1, and the queue is full when (tail + 1) mod N == head. Second, choose N as a power of two so the wrap is (i + 1) & (N - 1): a single AND instruction instead of a division, which matters on the Cortex-A cores of a Raspberry Pi where integer division is comparatively slow. An alternative design uses ever-increasing counters and relies on unsigned wraparound; the masked version is easier to reason about and is what this lesson uses.
Note what is absent: no allocation after construction, no pointers, no node freelist. The whole queue is one fixed-size object whose footprint is known at compile time, which fits the no-heap discipline this module applies to embedded targets.
The release/acquire handoff in code
4 min readThe ownership rule removes write/write races, but it does not answer the visibility questions: the consumer must not read a slot before the producer's write to it is visible, and the producer must not overwrite a slot before the consumer has finished copying out of it. Two synchronizing pairs solve both, using only the memory orders from the atomics lesson. Put this class in spsc.hpp:
#include <array>
#include <atomic>
#include <cstddef>
template <typename T, std::size_t N>
class SpscQueue {
static_assert(N >= 2 && (N & (N - 1)) == 0);
alignas(64) std::atomic<std::size_t> head_{0};
alignas(64) std::atomic<std::size_t> tail_{0};
alignas(64) std::array<T, N> buf_{};
public:
bool push(const T& v) {
const auto t = tail_.load(std::memory_order_relaxed);
const auto next = (t + 1) & (N - 1);
if (next == head_.load(std::memory_order_acquire))
return false;
buf_[t] = v;
tail_.store(next, std::memory_order_release);
return true;
}
bool pop(T& out) {
const auto h = head_.load(std::memory_order_relaxed);
if (h == tail_.load(std::memory_order_acquire))
return false;
out = buf_[h];
head_.store((h + 1) & (N - 1), std::memory_order_release);
return true;
}
};
Walk through push. The relaxed load of tail_ reads a variable only this thread writes, so it needs no synchronization at all. The acquire load of head_ checks for full; it pairs with the consumer's release store of head_, which happens after the consumer has copied out of a slot, so seeing an advanced head guarantees the consumer's read of that slot completed before the producer overwrites it. Then the plain write buf_[t] = v, then the release store of tail_. That release store publishes the slot write: when the consumer's acquire load of tail_ reads the value this store wrote, the two operations synchronize, and everything sequenced before the store (including the slot write) happens-before everything after the load (including the slot read). pop is the mirror image. If an acquire load reads an older value, it simply reports stale but conservative information: "still full" or "still empty", which is safe.
Producer writes the slot: a plain store to
buf_[t], ordered before step 2 by the release.Producer releases tail:
tail_.store(next, release)publishes the slot write.Consumer acquires tail: the acquire load reads the new value and synchronizes with step 2.
Consumer reads the slot: the plain load of
buf_[h]is guaranteed to see step 1.Consumer releases head: after copying out,
head_.store(..., release)frees the slot.Producer acquires head: before reusing the slot, the acquire load pairs with step 5.
Why not seq_cst everywhere? A single total order is needed for algorithms where each thread writes one variable and then reads the other (the Dekker shape). This design never does that: each variable has one writer, and pairwise visibility is all it needs. On x86-64, acquire loads and release stores compile to ordinary mov instructions because the hardware's ordering already covers these cases; on aarch64 (Raspberry Pi 4 and 5), GCC emits ldar for the acquire loads and stlr for the release stores. There is no locked read-modify-write and no system call anywhere in the queue. The Linux kernel uses exactly this pairing internally, spelled smp_store_release and smp_load_acquire, as its memory-barriers documentation describes.
This class is correct only with exactly one producer thread and one consumer thread for its whole lifetime. A second thread calling push reintroduces a write/write race on tail_ and on the slots, and nothing in the type system stops it. Document the contract, and in debug builds consider asserting the calling thread's id.
Stress-test it, then benchmark it against a mutex
2 min readConcurrency bugs hide in rare interleavings, so verification means forcing those interleavings millions of times. The standard SPSC stress test: the producer pushes the sequence numbers 0 to total - 1, spinning while push returns false; the consumer pops and asserts that every value equals its expected counter. Any lost, duplicated, reordered, or torn item trips the assert. A small capacity (8 below) forces the full and empty boundaries constantly; repeat with a large capacity (1024) to exercise the steady-state path. This is stress.cpp, using the header above:
#include <cassert>
#include <cstdio>
#include <thread>
#include "spsc.hpp"
int main() {
SpscQueue<unsigned, 8> q;
constexpr unsigned total = 10'000'000;
std::thread producer([&] {
for (unsigned i = 0; i < total; ++i)
while (!q.push(i)) {}
});
std::thread consumer([&] {
unsigned expected = 0, v = 0;
while (expected < total) {
if (q.pop(v)) {
assert(v == expected);
++expected;
}
}
});
producer.join();
consumer.join();
std::printf("ok: %u items in order\n", total);
}
g++ -Wall -Wextra -O2 -std=c++20 stress.cpp -o stress -pthread
./stress
On success the program prints ok: 10000000 items in order; a failed assert aborts it. We built and ran exactly this program: it printed that line with -O2, and again with -fsanitize=thread -O1 -g, with no ThreadSanitizer report. Then build again with -fsanitize=thread -O1 -g in place of -O2 and run: ThreadSanitizer should report no races. A later lesson covers sanitizers in depth; here it is a second, independent witness that the ordering is right.
For the benchmark, wrap a std::deque<unsigned> in a class with the same push/pop signatures, each taking a std::lock_guard<std::mutex> and returning false when full or empty. Keep the spin loops identical on both sides so you measure the queues, not the blocking policy. Time the whole run with std::chrono::steady_clock, use the same item count, repeat several times, and report items per second. Pin the process to two chosen cores with taskset -c 2,3 ./bench to reduce migration noise; on a Pi, pick any two cores. Your numbers depend on the core, frequency, and cache, so report your own measurements rather than trusting anyone else's. For scale, our run of 5 million items through a capacity-8 ring and through a mutex-guarded deque of capacity 7, on a 12-thread x86-64 machine without pinning, gave about 37 to 70 million items per second for the ring and 2 to 3 million for the mutex queue in three repetitions.
What should you expect qualitatively? An uncontended mutex lock/unlock pair is still two atomic read-modify-write operations plus bookkeeping, and a contended one adds futex syscalls and sleep/wake latency. The SPSC path is loads and stores only, so it typically wins on throughput and on worst-case handoff latency for this two-thread shape. The honest counterpoint: spinning burns a whole core while the queue is empty or full, while a mutex consumer sleeps and frees the CPU. Lock-free buys latency with CPU time. And with many producers, SPSC is simply not applicable, which is where the next section goes.
Internals: cache lines, atomic_ref, and many producers
4 min readThe alignas(64) in the class is not decoration. Cache coherence works on whole cache lines, 64 bytes on x86-64 and on the Cortex-A72 of the Pi 4 and the Cortex-A76 of the Pi 5. If head_ and tail_ sit on the same line, every store by one core invalidates the other core's copy of that line, so the line bounces between cores even though the threads never touch the same variable. That is performance loss caused by independent variables sharing one cache line, so each write invalidates the other core's copy, and it can cost more than the lock you removed. alignas(64) on each index gives each writer its own line, at the cost of a few dozen padding bytes. C++17 offers std::hardware_destructive_interference_size in <new> for this purpose, but its value is implementation-defined and GCC warns about ABI stability when you use it in headers, so many codebases targeting these machines write alignas(64) directly. (On our x86-64 GCC 13 build the constant printed 64.)
Going deeperstd::atomic_ref (C++20): atomics over a plain object
std::atomic_ref<T> applies atomic operations to an existing non-atomic object for the reference's lifetime:
#include <atomic>
#include <cstddef>
alignas(std::atomic_ref<std::size_t>::required_alignment)
std::size_t tail = 0;
void publish(std::size_t next) {
std::atomic_ref<std::size_t> ref(tail);
ref.store(next, std::memory_order_release);
}
Three rules: the object must be aligned to required_alignment, which can exceed alignof(T); the object must outlive every reference to it; and while any atomic_ref exists, all accesses must go through references, never plain reads or writes. The payoff for this lesson: a ring buffer placed in shared memory between two processes (shm_open plus mmap) cannot portably rely on std::atomic objects working across address spaces, but an atomic_ref over a suitably aligned plain integer in the shared mapping is the standard tool, provided is_lock_free() is true. The same SPSC design then connects processes, not just threads.
Going deeperMPMC and the Michael-Scott queue
With two producers, the single-writer rule dies: advancing tail must become a CAS loop, with the ABA hazards from the CAS lesson. The classic lock-free MPMC design is the Michael-Scott queue (Maged Michael and Andrew Scott, 1996): a linked list with a sentinel node and shared head and tail pointers. Enqueue CASes the new node onto tail->next, then CASes tail forward; if the second CAS lags, other threads help complete it. Dequeue CASes head past the sentinel. Under contention, every thread fights over the same two pointers, so the cache lines bounce and CASes retry.
The genuinely hard part is deciding when a removed node can be freed, given that other threads may still hold pointers to it: a popped node cannot be deleted while another thread might still dereference it, or you get use-after-free and ABA. Practical designs use hazard pointers, epoch-based reclamation, or tagged pointers. Bounded MPMC rings such as Vyukov's queue replace the shared tail with per-slot sequence counters; know the name.
The embedded alternative keeps this lesson's simplicity: give each producer its own SPSC queue and let the consumer drain them in turn. No CAS anywhere, per-producer order preserved, and the only cost is polling several queues. Reach for that decomposition first when the topology allows it.
In a real pipeline the producer usually reads from a file descriptor: a device file, a pipe, or a socket. That descriptor is a resource with a lifetime, and the next lesson, "A RAII file descriptor wrapper", builds the class that owns it and closes it exactly once, so the capture thread feeding your queue cannot leak it.
Key takeaways
- With one producer and one consumer, each index has a single writer, so no CAS and no lock is needed.
- A release store of tail publishes the slot write; the consumer's acquire load of tail makes that write visible.
- head_ and tail_ must sit on different 64-byte cache lines (alignas(64)) or false sharing bounces the line between cores.
- Michael-Scott MPMC queues need CAS plus safe memory reclamation; per-producer SPSC queues often avoid both.
Reflect
- Explain to a colleague, in two sentences: implement a bounded SPSC ring buffer using only atomic loads and stores with release and acquire ordering
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
- Man pagepthreads(7): POSIX threads
- Man pagetaskset(1): set or retrieve CPU affinity
- DocumentationLinux kernel memory barriers
Official documentation first. Links checked when the lesson was published.