Sub topic 13
A Lock-Free Single-Producer, Single-Consumer Queue
This chapter assumes you know how a ring buffer works with head and tail indices, free-running unsigned indices, and power-of-two masking. It also assumes you can read basic C, including stdatomic.h. Here you will turn the free-running-index ring into a queue that two threads share without a lock.
When a lock is not needed
A ring buffer is a good fit for handing data from one thread to another. One thread only adds items (the producer), and one thread only removes them (the consumer). This is called single-producer, single-consumer, or SPSC.
The key property is that each index has exactly one writer:
- Only the producer writes
tail. - Only the consumer writes
head.
Each thread reads the other thread's index but never changes it. Because no two threads write the same variable, there is no write-write race, so no lock is needed. A mutex would also add blocking, which is a problem in audio callbacks and interrupt handlers.
The code
#include <stdatomic.h>
#include <stdbool.h>
#include <stdint.h>
#define CAP 8u /* power of two */
typedef struct {
int data[CAP];
_Atomic uint32_t head; /* written only by the consumer */
_Atomic uint32_t tail; /* written only by the producer */
} spsc_t;
bool spsc_push(spsc_t *q, int v) { /* producer thread only */
uint32_t t = atomic_load_explicit(&q->tail, memory_order_relaxed);
uint32_t h = atomic_load_explicit(&q->head, memory_order_acquire);
if (t - h == CAP) return false;
q->data[t & (CAP - 1u)] = v;
atomic_store_explicit(&q->tail, t + 1u, memory_order_release);
return true;
}
bool spsc_pop(spsc_t *q, int *out) { /* consumer thread only */
uint32_t h = atomic_load_explicit(&q->head, memory_order_relaxed);
uint32_t t = atomic_load_explicit(&q->tail, memory_order_acquire);
if (t == h) return false;
*out = q->data[h & (CAP - 1u)];
atomic_store_explicit(&q->head, h + 1u, memory_order_release);
return true;
}Walk through spsc_push:
- The producer reads its own
tail. No other thread changes it, so a relaxed load is enough. - It reads
headwith acquire ordering to learn how far the consumer has gone. - If
t - h == CAP, the queue is full and the push returnsfalse. Unsigned subtraction stays correct after the indices overflow. - It writes the item into the slot
t & (CAP - 1u). - It publishes the new tail with a release store.
spsc_pop mirrors this. It reads its own head relaxed, reads tail with acquire, copies the item out, and then publishes the new head with a release store.
Why the ordering matters
The order of operations is part of the design. The data write must become visible to the consumer no later than the new tail. Without ordering, the compiler or CPU may reorder the stores. The consumer could then see the new tail and read a slot that still holds old data.
- The producer's release store of
tailguarantees that the slot write happens before the index update, as seen by another thread. - The consumer's acquire load of
tailguarantees that if it sees the new index, it also sees the slot contents.
The same pairing works in the other direction for head. The consumer finishes reading a slot before it releases the new head. The producer acquires head before it reuses that slot. This stops the producer from overwriting data that is still being read.
The next chapter explains acquire and release ordering in more detail.
Common errors
- More than one producer or consumer. Two producers can both read the same
tailand write the same slot. This design is only correct for one thread on each side. - Capacity that is not a power of two. The mask
CAP - 1uand the wraparound oft - hboth rely on it. - Plain
uint32_tindices. Without_Atomic, the cross-thread reads are a data race, which is undefined behavior in C. - Overwrite-oldest policy. Overwriting makes the producer modify
head, which breaks the one-writer rule. Use reject-on-full here.
Exercise
In spscpop, why does the consumer read tail with memoryorderacquire, and what could go wrong if it used memoryorder_relaxed?
Show answer
The acquire load pairs with the producer's release store of tail. It guarantees that when the consumer sees the new tail, it also sees the data the producer wrote to the slot before publishing. With a relaxed load, the consumer could see the updated tail but still read stale slot contents, because nothing orders the slot write before the index update.