Section 14.15

Ring buffer

Definition

A ring buffer, also called a circular buffer, is a queue stored in a fixed array §14.5 whose slots are reused in a cycle: after the last slot comes slot 0. A read index marks the oldest stored item and a write index the next free slot; each store or removal advances one index by one slot. Memory is reserved once, items never move, and each operation takes constant time. A design must state how it tells full from empty, because in both states the two indexes can be equal.

The idea

A serial port receives bytes through an interrupt §6.11, a hardware signal that suspends the main program to run a short function called an interrupt handler §6.12. The handler must store each byte at once; the main program reads them later, in bursts. A plain array filled from the front runs out of room after one pass, shifting unread bytes forward wastes time, and allocating memory per byte is slow and can fail.

Bend the array into a circle, like a clock face. The writer moves clockwise, storing items, and the reader follows, removing them; the stored items are the arc between the two, and the writer reuses slots the reader has emptied. The circle creates one ambiguity: reader and writer point at the same slot both when the reader has caught up (empty) and when the writer is a full lap ahead (full).

How it works

The parts are an array of NN slots numbered 0 to N−1N - 1, a read index rr that holds the slot of the oldest stored item, and a write index ww that holds the slot for the next item. To store, check that the buffer is not full, write slot ww, then advance ww. To remove, check that it is not empty, read slot rr, then advance rr. Advancing means i←(i+1)modNi \leftarrow (i + 1) \bmod N, where amodNa \bmod N is the remainder of aa divided by NN, so the slot after N−1N - 1 is 0.

Three schemes tell full from empty.

  1. Leave one slot unused. Empty means r=wr = w; full means (w+1)modN=r(w + 1) \bmod N = r. The writer never catches up with the reader, so r=wr = w can only mean empty. The capacity is N−1N - 1.

  2. Keep a count of stored items: 0 means empty and NN means full, so all NN slots are used. Both sides change the count, so it needs an atomic operation §9.8, one that no other code can observe half done, or a lock.

  3. Free-running counters. rr and ww count all items ever removed and stored and are never reduced modulo NN; the item with counter value cc is in slot cmodNc \bmod N. The number stored is w−rw - r, computed with the same unsigned wraparound §4.16 as the counters, so empty means w−r=0w - r = 0 and full means w−r=Nw - r = N. The slots stay consecutive across a counter wrap only when NN is a power of two. The Linux kernel’s kfifo works this way.

With one producer and one consumer, schemes 1 and 3 need no lock: only the producer writes ww, and only the consumer writes rr. The order of memory accesses still matters. If the new ww becomes visible before the item’s bytes, the consumer reads old bytes, and the compiler may reorder accesses that way even on a single-core microcontroller §6.1 whose producer is an interrupt handler. Acquire-release ordering §9.11, from the 2011 C and C++ standards [78, 247], prevents it: the writes a thread makes before a store in release order are visible to any thread whose load in acquire order reads the stored value.

Two producers break this recipe: both can read the same ww, write slot ww and publish w+1w + 1, losing one item. Several producers need a lock, or an atomic compare-and-swap §9.9, which changes a value only if it still holds the value read before, to claim a slot. When full, a design refuses the new item, makes the producer wait, or overwrites the oldest item. Trace buffers often overwrite to keep the newest data; the producer then also advances rr, breaking the rule that only the consumer writes rr, and the lost data must be counted, as the tracing buffer loss §14.32 entry explains.

Worked example

One slot unused, N=4N = 4.

  1. Start with r=w=0r = w = 0: the buffer is empty.

  2. Store A, B and C in slots 0, 1 and 2; ww becomes 3.

  3. To store D, check (3+1)mod4=0(3 + 1) \bmod 4 = 0, which equals rr: the buffer is full, with 3 items in 4 slots.

  4. Remove A from slot 0, so r=1r = 1. Now (3+1)mod4=0(3 + 1) \bmod 4 = 0 differs from rr, so store D in slot 3, and ww wraps to 0.

  5. With r=1r = 1 and w=0w = 0, slots 1, 2 and 3 hold B, C and D. The buffer is full again, since (0+1)mod4=1=r(0 + 1) \bmod 4 = 1 = r, and holds (w−r+N)modN=(0−1+4)mod4=3(w - r + N) \bmod N = (0 - 1 + 4) \bmod 4 = 3 items.

Free-running 32-bit counters, N=4N = 4. The largest 32-bit unsigned value is 232−1=4,294,967,2952^{32} - 1 = 4{,}294{,}967{,}295. Let r=4,294,967,294r = 4{,}294{,}967{,}294 and store three items: ww reaches 4,294,967,2974{,}294{,}967{,}297, which wraps to 4,294,967,297−232=14{,}294{,}967{,}297 - 2^{32} = 1. The count w−rw - r modulo 2322^{32} is 1−4,294,967,294+4,294,967,296=31 - 4{,}294{,}967{,}294 + 4{,}294{,}967{,}296 = 3, correct. The items, with counter values 4,294,967,2944{,}294{,}967{,}294, 4,294,967,2954{,}294{,}967{,}295 and 0, occupy slots 2, 3 and 0, consecutive because 2322^{32} is a multiple of 4. With N=3N = 3, both 4,294,967,295=3×1,431,655,7654{,}294{,}967{,}295 = 3 \times 1{,}431{,}655{,}765 and the next value, 0, map to slot 0, so the second item overwrites the first.

Stated precisely

Scheme 1, with NN slots and indexes 0≤r<N0 \le r < N and 0≤w<N0 \le w < N. The stored items are in slots r,r+1,…,w−1r, r + 1, \dots, w - 1, each taken modulo NN, oldest first, and their number is (w−r+N)modN(w - r + N) \bmod N. The buffer is empty if and only if r=wr = w, and full if and only if (w+1)modN=r(w + 1) \bmod N = r. The capacity is N−1N - 1.

Scheme 3, with bb-bit unsigned counters. The number stored is (w−r)mod2b(w - r) \bmod 2^b, correct across a wrap because it never exceeds NN and N<2bN < 2^b. Consecutive counter values cc give consecutive slots cmodNc \bmod N across the wrap if and only if NN divides 2b2^b, that is, NN is a power of two. Empty holds if and only if w=rw = r, full if and only if (w−r)mod2b=N(w - r) \bmod 2^b = N. For a power of two NN, cmodNc \bmod N equals the bitwise AND of cc with N−1N - 1, so slots can be computed with a mask; for other NN the mask is wrong.

Ordering contract for one producer and one consumer. Each index has one writer and is read and written indivisibly. The producer writes slot ss before storing the advanced ww in release order. The consumer reads slot ss only after a load of ww in acquire order shows the item, and stores the advanced rr in release order only after finishing the read. The producer rewrites slot ss only after an acquire load of rr shows it freed.

Limits and common mistakes

An index must be read and written in one access. On an 8-bit processor, a 16-bit index is stored as two separate bytes, and the other side can read one new byte and one old byte.

Free-running counters with a size that is not a power of two fail only at the counter wrap. At 1,000 items per second a 32-bit counter wraps after 232/1000≈4,294,9672^{32} / 1000 \approx 4{,}294{,}967 seconds, about 49.7 days, so short tests miss the fault.

Questions answered

How are full and empty states distinguished when indices match?

A ring buffer, a fixed array used as a queue whose read and write indexes wrap from the last slot to slot 0, tells full from empty by one of three rules, and matching indexes mean what the chosen rule says.

With 4 slots and one unused, read index 1 with write index 0 means full, with 3 items, and both indexes 0 means empty. Also, the producer must write an item before publishing the new write index, and the consumer must finish reading a slot before publishing the new read index.

Related entries: Queue and FIFO (§14.14), Tracing buffer loss (§14.32), Concurrency versus parallelism (§9.1), Acquire-release ordering (§9.11), Bounded queue (§9.31). Further reading: [78, 247].