1. Today's topic
SPSC means Single Producer / Single Consumer: exactly one producer modifies head and one consumer modifies tail. Nested interrupts that re-enter the producer can violate that assumption too. Such a ring suits fast paths:
UART ISR -> EC25 parser task
ADC DMA ISR -> ADC processing task
CAN RX ISR -> protocol task
DMA completion -> buffer-owner taskThe main idea: SPSC is simple precisely because contention over the same indices has been excluded in advance.
2. Why this matters in your projects
For EC25 UART, it is preferable to pass a byte stream or chunk descriptors without using an RTOS queue for every byte. For ADC DMA, put descriptors for ready blocks into the SPSC ring rather than samples. For CAN/RS-485, the ISR quickly drains the hardware FIFO and passes a descriptor to the owner task.
3. Theory
When SPSC cannot be used
One SPSC ring cannot serve two ISR producers or two consumer tasks. That is MPSC/MPMC and requires a different algorithm.
Publication problem
The producer must write the slot first and only then publish head.
slot = item
store-release(head)The consumer must first observe head using acquire, then read the slot:
load-acquire(head)
item = slotC11 atomics
volatile is insufficient. Here head and tail must be atomic_uint and local counters unsigned int; initialize them before starting either participant. ATOMIC_INT_LOCK_FREE checks that atomic type, but also verify that the target implementation, memory and generated instructions are suitable for ISR use.
_Static_assert(ATOMIC_INT_LOCK_FREE == 2,
"SPSC atomic indices must always be lock-free");Monotonic counters
These counters are not unbounded monotonic values: unsigned arithmetic wraps. With valid initialization and a bounded producer/consumer distance, occupancy is the modular difference:
used = head - tail;
index = counter & (CAPACITY - 1U);The shown mask requires a nonzero power-of-two capacity below the counter range. Use a conservative bound no greater than half that range and enforce it at compile time; SPSC_MASK is capacity minus one. Do not reset indices while either participant is active.
Producer implementation
static bool spsc_try_push(spsc_ring_t *ring, const rx_descriptor_t *item)
{
unsigned int head = atomic_load_explicit(&ring->head, memory_order_relaxed);
unsigned int tail = atomic_load_explicit(&ring->tail, memory_order_acquire);
if (head - tail >= SPSC_CAPACITY) {
ring->producer_overflows++;
return false;
}
ring->slots[head & SPSC_MASK] = *item;
atomic_store_explicit(&ring->head, head + 1U, memory_order_release);
return true;
}Consumer implementation
static bool spsc_try_pop(spsc_ring_t *ring, rx_descriptor_t *item)
{
unsigned int tail = atomic_load_explicit(&ring->tail, memory_order_relaxed);
unsigned int head = atomic_load_explicit(&ring->head, memory_order_acquire);
if (head == tail) {
return false;
}
*item = ring->slots[tail & SPSC_MASK];
atomic_store_explicit(&ring->tail, tail + 1U, memory_order_release);
return true;
}Why CAS is unnecessary
Only the producer modifies head and only the consumer modifies tail, so the indices need no CAS. Releasing tail and acquiring it in the producer are also necessary: they prevent slot reuse before the consumer finishes reading.
Task notification as a doorbell
The ring stores data; a task notification is a retained wakeup signal. Notify after every successful publication; an ISR uses the appropriate FromISR operation and port-specific yield request. Reserve a notification index for this protocol. Notification count is not ring occupancy. Consumer pattern:
for (;;) {
while (spsc_try_pop(&ring, &desc)) {
process(desc);
}
ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
}4. Common mistakes
- Using SPSC with two producers.
- Using volatile head/tail instead of atomics.
- Making every operation memory_order_relaxed.
- Publishing head before writing the slot.
- Letting the producer change tail.
- Implementing overwrite-oldest by letting the producer update tail.
- Using head > tail after wraparound.
- Not checking whether atomics are lock-free for ISR use.
- Making the consumer task spin in a loop.
- Treating a notification as a queue element.
- Notifying only on a naive EMPTY->NONEMPTY transition and causing a lost wake-up.
- Ignoring overflow.
- Reading diagnostic fields without synchronisation and causing a data race.
5. Practical task
Create SPSC_POLICY.md:
# SPSC policy
1. Every SPSC ring has exactly one producer.
2. Every SPSC ring has exactly one consumer.
3. Producer exclusively modifies head.
4. Consumer exclusively modifies tail.
5. Element data is published before head.
6. Slot reuse occurs only after tail publication.
7. Indices use lock-free atomics.
8. Capacity is a power of two.
9. Overflow policy is explicit.
10. Wake-up notification is not the data source.
11. Large payloads are passed by handles.
12. Every ring exposes overflow diagnostics.Implement a ring for dma_desc_t and test:
empty pop
push/pop
FIFO order
full condition
reuse after drain
wraparound near UINT32_MAXThen create a host stress test: the producer thread writes 0..9 999 999, and the consumer checks the order. Build with ThreadSanitizer.
6. What to try next
- Integrate the SPSC descriptor ring with the DMA buffer pool from lesson 51.
- Compare ISR duration for xQueueSendFromISR() versus SPSC push + task notification.
- Check ESP32 core affinity: producer ISR and consumer task on the same core or different cores.
Exercise
A ring has capacity 8, head=10 and tail=6. Using the lesson’s monotonic-counter model, calculate occupancy and the next producer slot. A second ISR then wants to push into the same ring: is the SPSC assumption still satisfied?
Self-check criteria: Give occupancy 4, slot 2 and reject two producers for one SPSC ring.
Show the supplied answer
Occupancy is 10-6=4. The next producer slot is 10 & (8-1)=2. A second producer violates SPSC; it needs a different algorithm or a separate ring. Neither task notifications nor volatile indices restore the one-writer assumption.