</>EmbeddedInterview

When is a ring buffer safe without locks?

HardData Structures & Algorithms

Short answer: When there is exactly one producer and one consumer, only the producer writes head and only the consumer writes tail, each index is a word-sized variable updated with a single atomic store, and the producer writes the data before publishing the new head (the consumer reads the data after seeing the new head). On a single-core MCU, volatile indices plus a compiler barrier are enough; on multi-core or weakly ordered CPUs, use C11 atomics with release/acquire ordering. With several producers or consumers you need a lock, a critical section, or a CAS-based design.

#include <stdatomic.h>
#include <stdbool.h>
#include <stdint.h>

#define N 256u
typedef struct {
    uint8_t data[N];
    _Atomic uint32_t head;      /* written only by the producer */
    _Atomic uint32_t tail;      /* written only by the consumer */
} spsc_t;

bool spsc_put(spsc_t *q, uint8_t b)                  /* e.g. in the UART RX ISR */
{
    uint32_t h = atomic_load_explicit(&q->head, memory_order_relaxed);
    uint32_t t = atomic_load_explicit(&q->tail, memory_order_acquire);
    if (h - t == N) return false;
    q->data[h & (N - 1)] = b;                                     /* 1. write data */
    atomic_store_explicit(&q->head, h + 1, memory_order_release);  /* 2. publish */
    return true;
}

bool spsc_get(spsc_t *q, uint8_t *b)                 /* e.g. in a task */
{
    uint32_t t = atomic_load_explicit(&q->tail, memory_order_relaxed);
    uint32_t h = atomic_load_explicit(&q->head, memory_order_acquire);
    if (h == t) return false;
    *b = q->data[t & (N - 1)];                                    /* read data after acquire */
    atomic_store_explicit(&q->tail, t + 1, memory_order_release);  /* free the slot */
    return true;
}

Why each rule matters

  • Single writer per index: if two producers both read head, both write the same slot and both increment: one item is lost. A read-modify-write without atomic operations is a race.
  • Ordering: without release/acquire (or barriers), the CPU or compiler may make the new head visible before the data, so the consumer reads stale data. Cortex-M0/M3/M4 execute in order and the compiler barrier is the main concern; Cortex-M7, Cortex-A and multi-core systems need real barriers (dmb).
  • Atomic index size: a 32-bit index on a 32-bit MCU is written in one instruction; a 64-bit index on a 32-bit MCU would not be atomic.
  • Cache coherency: with DMA or another core without coherent caches, the buffer needs cache maintenance or uncached memory.

Interview follow-up: "What if two ISRs both write?" Make the producer side a critical section (mask interrupts briefly), or give each ISR its own queue.