Skip to content

Ring Buffers

F32Buffer, F64Buffer and I16Buffer are lock-free single-producer, single-consumer rings. Their storage is mapped twice, so a read is always one contiguous zero-copy window across the wrap.

Capacity

Any capacity from 1 up, and capacity is exactly the number you passed — on every machine. It need not be a power of two.

What is rounded is the mapping behind the ring: up to a power of two, because indexing is a mask, and up to a whole number of pages, because the double mapping is built from them (4 KiB on Linux x86-64, 16 KiB on macOS arm64, 64 KiB allocation granularity on Windows). That is address space, not room — a ring of 1,000 holds 1,000 and refuses the next sample — and it costs nothing per call. A capacity just past a power of two maps nearly twice what it holds; one that is a power of two and spans a page maps exactly itself.

Two surfaces, one ring

You are Read with Write with
a consumer thread, producer apart wait(n) — blocks write(arr)
one thread doing both peek(n) — never write_some(arr)

Threaded. One producer thread calls write; one consumer thread calls wait / consume. write is non-blocking and refuses the whole call if the ring has no room — it copies nothing and leaves your array untouched, so you still hold the data and can retry. Nothing is dropped unless you discard it; dropped counts the samples in refused calls, not lost samples. wait blocks the consumer and releases the GIL so the producer can run concurrently.

Single-threaded. wait would deadlock a caller that is its own producer, so peek(n) returns the same zero-copy view when n samples are there and None when they are not yet. None means not yet and nothing else: a closed ring with fewer than n left raises EOFError, and n > capacity raises ValueError, exactly as wait does. write_some takes what fits and returns the count, never refusing and never touching dropped — the only way to feed a chunk larger than the ring. space is the room a write is guaranteed to find; reset() empties and reopens the ring (both sides must be idle).

Both surfaces release with consume(k); k < n keeps the overlap, which is how overlapped frames are read.


Examples

Producer / consumer (threaded)

From src/doppler/examples/buffers_demo.py. write() never blocks, so the producer waits for space; close() is how the consumer learns there is no more, and it arrives as EOFError once the ring is drained.

import threading

import numpy as np

from doppler.buffer import F32Buffer, F64Buffer, I16Buffer

IQ16 = np.dtype([("i", "<i2"), ("q", "<i2")])


# A ramp in each width's own element, so a sample says where it came from.
def ramp_complex(dtype):
    return lambda n: np.arange(n).astype(dtype)


def ramp_iq16(n):
    x = np.zeros(n, dtype=IQ16)
    x["i"] = np.arange(n)
    return x


# Two threads. wait() releases the GIL while it spins, so the producer
# runs; close() is how the consumer learns there is no more.
buf = F64Buffer(4096)
got = []


def producer():
    for k in range(8):
        while buf.space < 512:  # write() never blocks: wait for room
            pass
        buf.write(np.full(512, k, dtype=np.complex128))
    buf.close()


t = threading.Thread(target=producer)
t.start()
try:
    while True:
        got.append(int(buf.wait(512)[0].real))
        buf.consume()
except EOFError:
    pass  # closed and drained: the normal end of a stream
t.join()

assert got == list(range(8)), "every block, once, in order"
assert buf.dropped == 0
buf.destroy()

One thread: any block in, exact frames out

wait(n) blocks until a producer on another thread delivers, so a caller that is its own producer would wait forever. peek(n) is the same zero-copy view without the wait — the frame, or None for "not yet" — and write_some takes what fits. Together they are the whole single-threaded pattern: feed, take every whole frame, repeat until the block is gone.

import threading

import numpy as np

from doppler.buffer import F32Buffer
from doppler.spectral import FFT


# A ramp, so every sample says where in the stream it came from: a frame
# that is off by one, duplicated or dropped shows up as a break in the
# sequence rather than as a plausible-looking block of signal.
def stream(start: int, n: int) -> np.ndarray:
    idx = np.arange(start, start + n)
    return (idx + 1j * idx).astype(np.complex64)


FFT_N = 1024
ring = F32Buffer(4096)  # four frames. SMALLER than the largest block below.

# What the device hands over: nothing is a multiple of FFT_N, and two of
# them are larger than the whole ring.
DRIVER_BLOCKS = [3000, 5000, 1700, 4096, 777, 2048, 6000, 1234]

fft = FFT(FFT_N, -1)
spectra: list[np.ndarray] = []
frames: list[np.ndarray] = []
produced = 0

for _ in range(6):
    for n in DRIVER_BLOCKS:
        block = stream(produced, n)
        produced += n

        # THE PATTERN. Feed what fits, take every whole frame, repeat until
        # the block is gone. `write_some` never refuses, so there is no
        # room to make first and no block too large; `peek` never blocks,
        # so one thread can do both jobs.
        fed = 0
        while fed < len(block):
            fed += ring.write_some(block[fed:])
            while (frame := ring.peek(FFT_N)) is not None:
                spectra.append(fft.execute_cf32(frame))  # straight in: no copy
                frames.append(frame.copy())  # kept past consume(): copied
                ring.consume()  # releases the frame that was lent

One thread: a chunk larger than the ring, overlapped frames out

From src/doppler/examples/ring_nonblocking_demo.py, which checks every frame against the input:

import numpy as np

from doppler.buffer import F32Buffer


def stream(start: int, n: int) -> np.ndarray:
    idx = np.arange(start, start + n)
    return (idx + 1j * idx).astype(np.complex64)


ring = F32Buffer(4096)
CAP = ring.capacity

ring.reset()
NFFT, HOP = 1000, 250
assert CAP % NFFT, "frames must straddle the wrap for this to show anything"
chunk = stream(0, 5 * CAP)
assert not ring.write(chunk[: CAP + 1]), "write() refuses what cannot fit"
refused = ring.dropped

fed = taken = 0
while fed < len(chunk):
    k = ring.write_some(chunk[fed:])
    fed += k
    drained = 0
    while (frame := ring.peek(NFFT)) is not None:
        assert frame.flags["C_CONTIGUOUS"], "the double-mapping's promise"
        assert np.array_equal(frame, chunk[taken * HOP :][:NFFT]), (
            f"frame {taken} is not the stream at hop {taken * HOP}"
        )
        ring.consume(HOP)  # release a hop, keep the overlap
        taken += 1
        drained += 1
    # A full ring holds a whole frame, so one side always moves. Without
    # this, a regression in either call is a hang rather than a failure.
    assert k or drained, "neither side made progress"

End of stream, then the same ring again

ring.close()
tail = ring.available
assert 0 < tail < NFFT
try:
    ring.peek(NFFT)
    raise AssertionError("a closed ring answered 'not yet'")
except EOFError:
    pass  # the rest of that frame is never coming: not None, an error
last = ring.peek(tail)  # what IS there can still be read
assert np.array_equal(last, chunk[-tail:])
ring.consume()

ring.reset()
assert not ring.closed and ring.available == 0 and ring.space == CAP
assert ring.write_some(stream(0, 8)) == 8
assert np.array_equal(ring.peek(8), stream(0, 8))

I16Buffer — raw ADC samples

numpy has no complex-integer dtype, so one q15 sample is a record, [("i", "<i2"), ("q", "<i2")]. Both faces speak it, which keeps the ring 1-D with one element per sample like its float siblings. The storage underneath is still interleaved int16, so .view() converts either way with no copy.

from doppler.buffer import I16Buffer
import numpy as np

IQ16 = np.dtype([("i", "<i2"), ("q", "<i2")])

buf = I16Buffer(4096)
adc_bytes = np.zeros(2048 * 2, dtype=np.int16).tobytes()   # ADC byte stream
raw = np.frombuffer(adc_bytes, dtype=IQ16)                  # zero-copy
buf.write(raw)

view = buf.wait(1024)       # shape (1024,), dtype IQ16
I = view["i"]               # strided int16 views, no copy
Q = view["q"]
flat = view.view(np.int16)  # interleaved I, Q, I, Q, ... — also no copy
buf.consume()

A bare int16 array — flat or (n, 2) — is refused with TypeError: it is not an array of samples. And a record refuses arithmetic (view + 1 raises) where a packed int32 would carry across the I/Q boundary and corrupt I silently, which is why it is a record.

A full ring

A full ring is not an error: write() refuses the block and returns False — you still hold it — and dropped counts what was refused.

buf = F32Buffer(1000)          # any size; not a power of two here
cap = buf.capacity            # 1000

buf.write(np.ones(cap, dtype=np.complex64))        # True
buf.write(np.ones(1, dtype=np.complex64))          # False: no room
buf.dropped                                         # 1 refused, none lost

The full walk through every refusal is src/doppler/examples/ring_refusals_demo.py; the rest of the suite is indexed on Ring Buffers.