circular buffer
lock-free programming
concurrency
data structures
buffer management

Lock-free circular buffer (SPSC ring buffer) in C++

Codemia Knowledge Hub ·

A circular lock-free buffer, or ring buffer, is a fixed-size queue that supports concurrent reads and writes without a mutex around every operation. It fits well when one thread produces data and another consumes it at high frequency. The simplest practical design is a single-producer, single-consumer (SPSC) buffer built with atomics and careful memory ordering.

Start with the single-producer, single-consumer case

"Lock-free" covers many designs, and they differ a lot in complexity. An SPSC buffer is much easier to reason about than a queue with many writers and many readers.

In the SPSC model:

  • one thread is the only writer
  • one thread is the only reader
  • both threads share a fixed array
  • the producer advances tail
  • the consumer advances head

Because each index has exactly one owner, the common case needs no compare-and-swap loops, which makes the code faster and easier to verify.

Representing the buffer as a ring

The array is treated as circular: when an index reaches the end, it wraps back to the beginning. A common implementation stores Capacity + 1 slots so that head == tail means empty, and the next position after tail colliding with head means full.

Here is a runnable C++ example:

cpp
1#include <array>
2#include <atomic>
3#include <cstddef>
4#include <iostream>
5
6template <typename T, std::size_t Capacity>
7class SpscRingBuffer {
8public:
9    bool push(const T& value) {
10        const auto tail = tail_.load(std::memory_order_relaxed);
11        const auto next = increment(tail);
12
13        if (next == head_.load(std::memory_order_acquire)) {
14            return false; // full
15        }
16
17        buffer_[tail] = value;
18        tail_.store(next, std::memory_order_release);
19        return true;
20    }
21
22    bool pop(T& value) {
23        const auto head = head_.load(std::memory_order_relaxed);
24
25        if (head == tail_.load(std::memory_order_acquire)) {
26            return false; // empty
27        }
28
29        value = buffer_[head];
30        head_.store(increment(head), std::memory_order_release);
31        return true;
32    }
33
34private:
35    static constexpr std::size_t StorageSize = Capacity + 1;
36
37    std::size_t increment(std::size_t index) const {
38        return (index + 1) % StorageSize;
39    }
40
41    std::array<T, StorageSize> buffer_{};
42    std::atomic<std::size_t> head_{0};
43    std::atomic<std::size_t> tail_{0};
44};
45
46int main() {
47    SpscRingBuffer<int, 4> queue;
48    queue.push(10);
49    queue.push(20);
50
51    int value = 0;
52    while (queue.pop(value)) {
53        std::cout << value << '\n';
54    }
55}

The example is deliberately narrow. It does not attempt multiple producers, blocking waits, dynamic growth or memory reclamation. That is a strength, because most production bugs in lock-free code come from overreaching.

Why the memory orders matter

The buffer works only if the consumer sees the written element before it sees the updated tail, and the producer sees the consumed slot before it reuses it. That is why the code uses memory_order_release when publishing a new index and memory_order_acquire when reading the other side's index.

The sequence is:

  1. producer writes element into the array
  2. producer stores the new tail with release semantics
  3. consumer loads tail with acquire semantics
  4. consumer can now safely read the published element

The same logic applies in reverse for head. If you weaken the ordering without understanding the consequences, the queue may pass tests on one machine and fail under load on another.

Telling full from empty

A ring buffer always needs a rule to distinguish full from empty. The implementation above sacrifices one slot:

  • empty when head == tail
  • full when increment(tail) == head

This keeps the logic simple. A separate count also works, but it adds shared state and more synchronization pressure.

If Capacity is a power of two, you can replace modulo with a bit mask for slightly faster wraparound, at the cost of more specialized code.

When you need more than SPSC

Many questions about lock-free circular buffers really mean MPMC (multi-producer, multi-consumer) queues, which are a different class of problem. With multiple producers or consumers, simple head and tail ownership is gone, and you usually need compare-and-swap, per-slot sequence numbers or a different data structure entirely.

If the requirement is genuinely MPMC, do not stretch an SPSC design until it breaks. Use an algorithm built for that case, or a well-tested library.

Mistakes that corrupt SPSC buffers

  • More than one producer or consumer. Calling an SPSC buffer from several threads on either side may look fine in light testing and corrupt data later.
  • Wrong memory ordering. Replacing acquire and release with relaxed operations everywhere can produce stale reads or reordered writes.
  • Index overflow. Less dramatic, but use unsigned index types and wrap in a controlled way.
  • Expensive element copies. A ring buffer is usually chosen for low latency, so avoid element types with costly copy behavior unless that tradeoff is acceptable.

Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms