#ring-buffer #spsc #compile-time #const-generics #sync #thread-safe

ringbuffer-spsc

A fast thread-safe single producer-single consumer ring buffer

14 releases

0.1.15 Sep 3, 2025
0.1.14 Sep 3, 2025
0.1.13 Feb 10, 2025
0.1.11 Jan 29, 2025
0.1.3 Jul 27, 2022

#95 in Concurrency

Download history 19429/week @ 2025-07-16 23545/week @ 2025-07-23 21731/week @ 2025-07-30 21803/week @ 2025-08-06 21494/week @ 2025-08-13 23660/week @ 2025-08-20 25502/week @ 2025-08-27 27001/week @ 2025-09-03 23015/week @ 2025-09-10 24145/week @ 2025-09-17 26113/week @ 2025-09-24 26572/week @ 2025-10-01 28485/week @ 2025-10-08 31064/week @ 2025-10-15 27554/week @ 2025-10-22 20178/week @ 2025-10-29

113,007 downloads per month
Used in 68 crates (via zenoh-transport)

EPL-2.0 OR Apache-2.0

13KB
119 lines

ringbuffer-spsc

A fast single-producer single-consumer ring buffer. For performance reasons, the capacity of the buffer is determined at compile time via a const generic and it is required to be a power of two for a more efficient index handling.

Example

Here below is reported the throughput example for convenience.

use ringbuffer_spsc::RingBuffer;
use std::{
    sync::atomic::{AtomicUsize, Ordering},
    time::{Duration, Instant},
};

fn main() {
    static COUNTER: AtomicUsize = AtomicUsize::new(0);
    let (mut tx, mut rx) = RingBuffer::<usize, 1_024>::init();

    std::thread::spawn(move || loop {
        if tx.push(1).is_some() {
            std::thread::yield_now();
        }
    });

    std::thread::spawn(move || loop {
        if rx.pull().is_some() {
            COUNTER.fetch_add(1, Ordering::Relaxed);
        } else {
            std::thread::yield_now();
        }
    });

    static STEP: Duration = Duration::from_secs(1);
    let start = Instant::now();
    for i in 1..=u32::MAX {
        std::thread::sleep(start + i * STEP - Instant::now());
        println!("{} elem/s", COUNTER.swap(0, Ordering::Relaxed));
    }
}

Performance

Tests run on an Apple M4, 32 GB of RAM.

$ cargo run --release --example throughput

Provides ~520M elem/s of sustained throughput.

531933452 elem/s
531134948 elem/s
528573235 elem/s
529276820 elem/s
523433161 elem/s
522780695 elem/s
527332139 elem/s
523041589 elem/s
520486274 elem/s
522570696 elem/s
...

Dependencies

~145KB