skip to content

How should a C++ UART receive interrupt hand bytes to the main loop, and why do the buffer indices need std::atomic with release and acquire rather than volatile?

level: seniorimportance: should knowfreq 45%

answer

  1. single producer, single consumer
  2. each index has one writer
  3. publish after writing the slot
  4. plain buffer, atomic indices
  5. lock-free or it can deadlock

basics

~20 s

Use a single-producer, single-consumer ring buffer: the handler writes the byte, then stores the head index with release; the main loop loads head with acquire before reading the slot. volatile indices give no ordering for the plain buffer writes.

solid answer

~40 s

A ring buffer with one writer per index needs no read-modify-write of shared state: the interrupt handler owns `head`, the main loop owns `tail`, and the buffer itself is a plain array. What it does need is **ordering**: the byte must be in `rx_buf` before the main loop sees the new `head`. Making the indices `std::atomic<std::size_t>` and storing `head` with `memory_order_release` after writing the slot, then loading it with `memory_order_acquire` before reading, gives exactly that, and it is a data-race-free program in the standard's terms. `volatile` indices do not: the compiler may move the plain buffer store after the volatile index store, and no fence is emitted. The atomics must be lock-free (`static_assert(std::atomic<std::size_t>::is_always_lock_free)`); on a single core, `std::atomic_signal_fence` is the compiler-only barrier the standard provides between a thread and its signal handler.

code

cpp · 32 lines
cpp
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <cstdio>

// Single producer (the UART receive interrupt), single consumer (the main loop).
constexpr std::size_t N = 64;                  // power of two
std::uint8_t rx_buf[N];                        // plain storage, published by head
std::atomic<std::size_t> head{0};              // written only by the handler
std::atomic<std::size_t> tail{0};              // written only by the main loop
static_assert(std::atomic<std::size_t>::is_always_lock_free);

void uart_rx_isr(std::uint8_t byte) {          // would read the data register
  std::size_t h = head.load(std::memory_order_relaxed);
  if (h - tail.load(std::memory_order_acquire) == N) return;  // full: drop
  rx_buf[h % N] = byte;
  head.store(h + 1, std::memory_order_release);   // publish the byte
}

bool uart_read(std::uint8_t& out) {             // main loop
  std::size_t t = tail.load(std::memory_order_relaxed);
  if (t == head.load(std::memory_order_acquire)) return false;  // empty
  out = rx_buf[t % N];
  tail.store(t + 1, std::memory_order_release);   // free the slot
  return true;
}

int main() {
  for (char c : "OK\n") if (c) uart_rx_isr(static_cast<std::uint8_t>(c));  // stand-in for interrupts
  std::uint8_t c;
  while (uart_read(c)) std::putchar(c);
}

go deeper

for a junior

Describe the ring buffer: the handler writes bytes and advances head, the main loop reads and advances tail.

for a middle

Explain why each index has one writer and why the byte must be visible before the new head.

for a senior

Show the release store and acquire load, the lock-free static_assert, and when atomic_signal_fence alone is enough.

for a principal

Standardise one interrupt-to-task queue for the codebase, with its overrun policy and the rules review enforces.

## The design: a single-producer, single-consumer ring A UART receive interrupt produces bytes and the main loop consumes them. The classic structure is a fixed-size ring buffer: - `rx_buf[N]`: the storage, a plain array of bytes. - `head`: the count of bytes written, changed **only** by the interrupt handler. - `tail`: the count of bytes read, changed **only** by the main loop. The buffer is empty when `head == tail` and full when `head - tail == N`. Because each index has exactly one writer, no read-modify-write of shared data happens, so the lost-update problem of a shared counter never arises. With `N` a power of two, `index % N` stays correct when the unsigned counters wrap. ## What can still go wrong: ordering The handler does two things: it writes the byte into `rx_buf[h % N]`, then it advances `head`. The main loop reads `head`, sees a new byte, and reads `rx_buf[t % N]`. That is only correct if the main loop can never see the new `head` before the byte itself is in the buffer. Two things can reorder those stores: 1. **The compiler.** It may move a plain store across a later store to a different object, including a volatile one; `volatile` orders volatile accesses only against each other. 2. **The core.** A multi-core part or a core with a write buffer can make stores visible in a different order, and `volatile` emits no barrier. ## Why release and acquire fix it `std::atomic` gives the ordering explicitly. The handler finishes the plain write, then `head.store(h + 1, std::memory_order_release)`. The main loop does `head.load(std::memory_order_acquire)` and only then reads the slot. A release store that an acquire load reads from creates a **happens-before** relation: every write before the release, including the plain store into `rx_buf`, is visible after the acquire. The same pairing on `tail` tells the handler a slot is free before it overwrites it. The memory-order rules themselves are a topic of their own; for this handoff, release on publish and acquire on consume is the whole recipe. The standard models an interrupt handler most closely as a **signal handler**, and there the rule is strict: a non-atomic access in the handler that conflicts with an unsequenced access in the interrupted code is a data race and undefined behaviour. With atomic indices and the buffer slots handed over by release and acquire, the program has no data race. ## Checks specific to interrupts | Concern | What to do | |---|---| | Atomic falls back to a lock | `static_assert(std::atomic<std::size_t>::is_always_lock_free);` (C++17); a locked atomic can deadlock the handler | | Handler calls library functions | only plain lock-free atomic operations and functions marked signal-safe are safe in a signal handler; no `new`, no `printf` | | Single core, want no hardware fence | `std::atomic_signal_fence(std::memory_order_release)` orders against a handler on the same thread and emits no fence instruction | | Buffer full | the handler drops or counts overruns; it must never wait for the main loop | The cost is small. For a Cortex-M target, Clang 21 compiles a release store of a word-sized atomic (through the same builtins `std::atomic` uses) to a `dmb sy` barrier followed by an ordinary `str`, and an acquire load to an `ldr` followed by `dmb sy`; `std::atomic_signal_fence` compiles to no instruction at all, since it only restrains the compiler. ## Handling overrun A full buffer is the one case where the handler cannot do its job. It must not wait, so it either drops the new byte, as the example does, or overwrites the oldest one, which needs the consumer's cooperation and is harder to get right. Either way, count overruns in a handler-owned atomic so the main loop can report them; a silent drop turns a timing problem into corrupt data that nobody can explain. ## What not to do - `volatile std::size_t head;` with a plain buffer: the compiler may store `head` before the byte. - A shared `count` that both sides increment and decrement: a read-modify-write race unless it is atomic. - A `std::mutex` in the handler: the main loop may hold it when the interrupt fires, and the handler then waits forever. The code example below runs on a host by calling the handler directly in place of interrupts.

  • When is std::atomic_signal_fence enough instead of a release store?
    When the handler and the main loop run on the same core, as with an interrupt on a single-core microcontroller. The standard defines `std::atomic_signal_fence` as ordering only between a thread and a signal handler on that thread: it stops compiler reordering and emits no hardware fence. Across cores or with a DMA engine, use real atomics and fences.
  • Why does each index need only one writer?
    If only the handler writes `head` and only the main loop writes `tail`, each side merely loads the other's index, so no read-modify-write of shared data exists and no update can be lost. Atomic loads and stores with release and acquire then suffice; no `fetch_add` or interrupt masking is needed.

  • Making head volatile guarantees the byte is stored first.
  • Release and acquire are only needed on multi-core chips.
  • A std::mutex inside the interrupt handler is a safe way to protect the buffer.
  • The buffer array itself must be std::atomic too.
  • Any std::atomic type is lock-free on a microcontroller.