← writing

two atomics, one cursor

summary: the head-tail rewrite. one flag bit makes the difference between "spin once and recover" and "lock to be safe". 0.2.5 ships tonight.

Hyperbridge Hyperbridge: a public concurrency detour work: 2022 technical note

Core idea: Hyperbridge's cursor design used one atomic index word to carry both position and lifecycle state, avoiding a lock in the cross-block race path.

One bit, two meanings. That is the trick that ships today as 0.2.5.

const CLOSED_FLAG:  usize = 1 << 63;
const CROSSED_FLAG: usize = CLOSED_FLAG;

The same bit, in Cursor::index, means different things at the two ends of the channel. On tail.index it is CLOSED_FLAG: producers see it and stop. On head.index it is CROSSED_FLAG: the consumer has stepped onto a block the producer no longer points at. The reused bit is the difference between "spin once and recover" and "lock to be safe" - the consumer can detect the cross-block race in the same load it uses to read the position.

For the bit reuse to work, the cursor needs both pieces it dereferences off the same atomic word. That is the cursor schema:

struct Cursor<T> {
    index: AtomicUsize,
    block: AtomicPtr<Block<T>>,
}

index carries the sequence position with that one flag at the top; block points at the current Block<T>. The channel keeps two cursors, head and tail, on separate cache lines.

I am not going to push more on this crate for a while. There is a moment in any library's life where the right thing is to leave it alone.