How would you design and validate a bounded lock-free SPSC ring buffer, including full/empty states, object lifetime, wraparound, and acquire-release ordering?
Show answer and explanation
With exactly one producer and one consumer, let the producer own head and the consumer own tail. One simple representation reserves a slot: head equal to tail means empty, while advancing head to tail means full, so physical size N stores at most N-1 elements. The producer constructs a free slot before a release-store to head; the consumer acquire-loads head before reading that object, destroys it, then release-stores tail so the producer's acquire-load can safely reuse the slot. Index arithmetic must wrap without overflow assumptions, and T's construction, move, and destruction contracts must be handled. Test capacity boundaries, many wraparounds, long stress runs, and sanitizer-supported misuse; also verify that the index atomics are lock-free on the target. The design is not MPSC or MPMC.
With exactly one producer and one consumer, let the producer own head and the consumer own tail. One simple representation reserves a slot: head equal to tail means empty, while advancing head to tail means full, so physical size N stores at most N-1 elements. The producer constructs a free slot before a release-store to head; the consumer acquire-loads head before reading that object, destroys it, then release-stores tail so the producer's acquire-load can safely reuse the slot. Index arithmetic must wrap without overflow assumptions, and T's construction, move, and destruction contracts must be handled. Test capacity boundaries, many wraparounds, long stress runs, and sanitizer-supported misuse; also verify that the index atomics are lock-free on the target. The design is not MPSC or MPMC.
Connect the conclusion directly to the type, lifetime, ownership, overload-resolution rule, or library contract present in the question. State implementation dependence or a violated precondition explicitly instead of merely guessing output.