Crate sling

source ·
Expand description

This crates provides a sequentially locking Ring Buffer. It allows for a fast and non-writer-blocking SPMC-queue, where all consumers read all messages.

Usage

There are two ways of consuming from the queue. If threads share a SharedReader through a shared reference, they will steal queue items from one anothers such that no two threads will read the same message. When a SharedReader is cloned, the new SharedReader’s reading progress will no longer affect the other one. If two threads each use a separate SharedReader, they will be able to read the same messages.


let buffer = RingBuffer::<_, 256>::new();

let mut writer = buffer.try_lock().unwrap();
let mut reader = buffer.reader();

std::thread::scope(|s| {
    let reader = &reader;
    for t in 0..8 {
        s.spawn(move || {
            for _ in 0..100 {
                if let Some(val) = reader.pop_front() {
                    println!("t: {}, val: {:?}", t, val);
                };
            }
        });
    }

    for i in 0..100 {
        writer.push_back([i, i, i]);
    }
});

Important!

It is also important to keep in mind, that slow readers will be overrun by the writer if they do not consume messages quickly enough. This can happen quite frequently if the buffer size is not large enough. It is advisable to test applications on a case-by-case basis and find a buffer size that is optimal to your use-case.

Structs

A fixed-size, non-write-blocking, ring buffer, that behaves like a SPMC queue and can be safely shared across threads. It is limited to only work for types that are copy, as multiple threads can read the same message.
Shared read access to its buffer. When multiple threads consume from the RingBuffer throught the same SharedReader, they will share progress on the queue. Distinct [RingBuffers] do not share progress.
Provides exclusive write access to the RingBuffer.