Tuqueque
This module provides TuQueQue[1], a lock-free, fallible MPSC queue of fixed size. Lock-free means that writes and reads both proceed without the use of a mutex, or any other lock of indefinite duration. Fallible means that enqueues and dequeues can both fail. MPSC is multiple producer, single consumer: many writers and only one reader. Fixed size is why writes can fail. Writes are why dequeues can fail.
The mechanism is simple and efficient: swap buffers. At any given instant, one buffer is the write queue (the enqueue), the other is the read queue (the dequeue). Writers contend to reserve queue space, using a single atomic word, write to their reservation, then commit the write length. This allows them to leapfrog each other ā until the queue is full.
At any instant, the reader (singular!) can dequeue, by swapping which queue is which. Writes may not be committed, in which case the reader must wait until they are. This can time out, but in the absence of enqueue-side use bugs, the dequeue will eventualy succeed, and no further writes will be reserved to that side after a swap.
Once it succeeds, the reader has a slice of whatever the queue carries. It can do reader stuff with the slice, and (after reading, please!) resize the dequeue half of the tuqueque, if desired. It is not a correctness issue for the halves to be unbalanced, temporarily or otherwise.
Tuned appropriately, this is about as good as it gets. All common memory is handled atomically, and cache-isolated to eliminate false sharing.
The most important invariant is that there must only be one reader. To facilitate this, writes are expected to proceed using a WriteHandle, a type-erased pointer to the queue exposing only the write-appropriate functions (and a bit of bookkeeping, itās two words wide).
The library maintains a read lock and will panic in safe modes if two reader-side functions ever overlap. Seriously, donāt do it. There are more ways to get the queue into an inconsistent state that way than the assertions can detect and surface.
This library has 100% line coverage, but is hot off the presses and yet to be used in anger. Caveat hacker.
Inspiration
TuQueQue is a port of a Rust library, swap-buffer-queue, many thanks to @wyfo! It makes some different choices, in a way which will be comprehensible to anyone familiar with both languages: the Zig version puts somewhat more responsibility for correct use in the hands of the user, and is able to pick up some small efficiencies in return. In principle, at least: in addition to NO WARRANTY, tuqueque comes with no benchmarks.
Like the cognitive fallacy. Pronounced tu-kyu-kway, if
possible. You can also say ĀæTu que que?, but you had better know who
youāre saying it to. ā©ļø