Implement a lock-free single-producer single-consumer (SPSC) ring buffer.
#include <stdatomic.h>
#include <stdbool.h>
#include <stdint.h>
#define RING_SIZE 1024u /* power of two */
typedef struct {
uint8_t buf[RING_SIZE];
_Atomic uint32_t head; /* written only by the producer */
_Atomic uint32_t tail; /* written only by the consumer */
} ring_t;
bool ring_push(ring_t *r, uint8_t v) /* producer: ISR, or thread A */
{
uint32_t h = atomic_load_explicit(&r->head, memory_order_relaxed);
uint32_t t = atomic_load_explicit(&r->tail, memory_order_acquire);
if (h - t == RING_SIZE) return false; /* full (indexes run freely and wrap) */
r->buf[h & (RING_SIZE - 1u)] = v;
atomic_store_explicit(&r->head, h + 1u, memory_order_release); /* publish after the data */
return true;
}
bool ring_pop(ring_t *r, uint8_t *v) /* consumer: task, or thread B */
{
uint32_t t = atomic_load_explicit(&r->tail, memory_order_relaxed);
uint32_t h = atomic_load_explicit(&r->head, memory_order_acquire);
if (h == t) return false; /* empty */
*v = r->buf[t & (RING_SIZE - 1u)];
atomic_store_explicit(&r->tail, t + 1u, memory_order_release); /* free the slot after reading */
return true;
}
Answers to the usual follow-ups
- Is it thread-safe? Yes for exactly one producer and one consumer, because each index has a single writer. Multiple producers or consumers need a lock or a CAS-based design.
- ISR writes, thread reads? That is the classic use; on a single-core MCU the ISR and the task never run truly in parallel, but the compiler must still not reorder the data write after the index update, which the atomics (or
volatile+ a compiler barrier) guarantee. - Where are barriers needed? The producer must make the data visible before the new head (release); the consumer must read the head before the data (acquire). On Cortex-M7, Cortex-A and multi-core parts these compile to
DMBs orLDAR/STLR. - Head/tail overflow? The indexes are free-running 32-bit counters;
h - tis still correct after they wrap because of unsigned arithmetic, and using allRING_SIZEslots needs no "one slot empty" rule. - Why a power-of-two size?
& (SIZE - 1)replaces a slow modulo, and wrap-around of the free-running counters stays consistent only if SIZE divides 2³². - No atomics (Cortex-M0, old compiler)? Make the indexes
volatile, aligned 32-bit (atomic loads/stores on Arm), and put a compiler barrier between the data write and the index update.