Sub topic 13
A Single-Producer Single-Consumer Ring Buffer
This chapter assumes you already know Atomics.load, Atomics.store, Atomics.wait, and Atomics.notify, and that you know how a sequentially consistent store publishes earlier writes to a thread that later loads it. It uses Node.js worker_threads so you can run the example without setting up cross-origin isolation.
The Idea
A ring buffer is a fixed-size array that wraps around: after the last slot, writing continues at slot 0. Two indices track the buffer's state:
headis the next slot the consumer will read. Only the consumer writes it.tailis the next slot the producer will write. Only the producer writes it.
Each index has exactly one writer, so the buffer needs no lock and no compare-and-swap. Each side reads the other side's index with Atomics.load and advances its own with Atomics.store.
When head === tail, the buffer is empty. To tell full apart from empty, the buffer always leaves one slot unused. It counts as full when advancing tail would make it equal head.
Publishing Data Safely
The order of operations matters. The producer writes the value into its slot first, then stores the new tail. That store is sequentially consistent, so a consumer whose Atomics.load sees the new tail is guaranteed to also see the slot's contents. The consumer does the reverse: it reads the slot first, then stores the new head. Only after that store can the producer safely overwrite the slot.
A Runnable Example
const { Worker, isMainThread, workerData } = require('node:worker_threads');
const HEAD = 0;
const TAIL = 1;
class RingBuffer {
static create(capacity) {
return new SharedArrayBuffer(8 + capacity * 4);
}
constructor(sab, capacity) {
this.capacity = capacity;
this.ctrl = new Int32Array(sab, 0, 2);
this.data = new Int32Array(sab, 8, capacity);
}
push(value) {
const tail = Atomics.load(this.ctrl, TAIL);
const next = (tail + 1) % this.capacity;
if (next === Atomics.load(this.ctrl, HEAD)) return false; // full
this.data[tail] = value;
Atomics.store(this.ctrl, TAIL, next); // publishes the value
Atomics.notify(this.ctrl, TAIL, 1);
return true;
}
pop() {
const head = Atomics.load(this.ctrl, HEAD);
if (head === Atomics.load(this.ctrl, TAIL)) return undefined; // empty
const value = this.data[head];
Atomics.store(this.ctrl, HEAD, (head + 1) % this.capacity); // frees the slot
Atomics.notify(this.ctrl, HEAD, 1);
return value;
}
pushBlocking(value) {
while (!this.push(value)) {
Atomics.wait(this.ctrl, HEAD, Atomics.load(this.ctrl, HEAD));
}
}
popBlocking() {
for (;;) {
const tail = Atomics.load(this.ctrl, TAIL);
const value = this.pop();
if (value !== undefined) return value;
Atomics.wait(this.ctrl, TAIL, tail);
}
}
}
const CAPACITY = 4;
if (isMainThread) {
const sab = RingBuffer.create(CAPACITY);
const ring = new RingBuffer(sab, CAPACITY);
new Worker(__filename, { workerData: sab });
for (let i = 1; i <= 10; i++) ring.pushBlocking(i);
ring.pushBlocking(-1); // sentinel: no more data
} else {
const ring = new RingBuffer(workerData, CAPACITY);
let sum = 0;
for (let v; (v = ring.popBlocking()) !== -1; ) sum += v;
console.log('sum', sum); // sum 55
}Atomics.wait only sleeps if the index still holds the value the waiter passed in. A wake-up therefore cannot be lost: if the other side moved the index between the check and the wait, wait returns 'not-equal' right away and the loop tries again.
Common Errors
| Mistake | Effect |
|---|---|
| Storing `tail` before writing the slot | The consumer can read a stale value |
| Two producers sharing one buffer | Both claim the same slot, and one value is lost |
| Using all `capacity` slots | Full and empty look identical (`head === tail`) |
| Reading indices with plain `ctrl[TAIL]` | The read races, and nothing orders it with the slot data |
Exercise
With CAPACITY set to 4, how many values can the buffer hold at once, and why?
Show answer
Three. One slot always stays empty so that a full buffer (next tail equals head) can be told apart from an empty one (head equals tail).
Exercise
Why does this design need no compareExchange, while the mutex from the earlier chapter does?
Show answer
Each index has exactly one writer: the producer owns tail and the consumer owns head. No two threads ever race to update the same location, so a plain atomic store is enough.