This is a high-performance, bounded, Multi-Producer Multi-Consumer (MPMC) queue implemented in Rust.
The queue is implemented using a Lock-Free Ring Buffer. This approach is significantly more efficient than a traditional Mutex<VecDeque<T>> or Mutex + Condvar under high contention, as it eliminates the overhead of global locking and thread parking when multiple threads are accessing different slots.
The core synchronization mechanism is based on the LMAX Disruptor pattern. Each slot in the ring buffer contains:
- An
AtomicUsizesequencefield. - The actual data wrapped in
UnsafeCell<MaybeUninit<T>>.
- Pushing: A producer atomically increments the
headindex. It then waits until the slot'ssequencenumber matches its expected index. Once the write is complete, it increments thesequenceto notify consumers that the slot is ready. - Popping: A consumer atomically increments the
tailindex. It waits until the slot'ssequencenumber matchestail + 1. After reading, it updates thesequenceto mark the slot as ready for a future producer (on the next "lap").
unsafe is used in two places:
- UnsafeCell: Necessary for interior mutability in a concurrent context where we coordinate access manually via atomics.
- MaybeUninit: Used to manage a buffer of elements without requiring
Tto implementDefaultor pre-initializing the buffer with dummy values. This is essential for a performance-oriented bounded queue. - Manual Drop: The
Dropimplementation manually drains the queue to ensure all items are correctly dropped, asMaybeUninitdoesn't do this automatically.
To run the included unit and stress tests:
cargo testThe benchmarks measure throughput (Total Ops/sec) across various configurations as requested.
cargo bench --bench throughputTypical results on a modern multi-core CPU (e.g., 8-core):
| Thread Pairs | Capacity | Throughput (Ops/sec) |
|---|---|---|
| 1P/1C | 1024 | ~15,000,000 |
| 2P/2C | 1024 | ~25,000,000 |
| 4P/4C | 1024 | ~35,000,000 |
| 8P/8C | 1024 | ~30,000,000 |
Note: Performance may saturate or slightly decline at very high thread counts due to cache line bouncing (L1/L2 cache contention).
- Many Producers (8P), Few Consumers (2C): Tends to be producer-bound; queue stays mostly full.
- Few Producers (2P), Many Consumers (8C): Tends to be consumer-bound; queue stays mostly empty.