6 releases

0.2.5 May 1, 2024
0.2.4 Nov 1, 2023
0.2.3 Sep 9, 2023
0.2.2 Jul 29, 2023
0.1.0 Mar 13, 2022

#75 in Concurrency

Download history 487/week @ 2024-04-04 525/week @ 2024-04-11 471/week @ 2024-04-18 637/week @ 2024-04-25 486/week @ 2024-05-02 528/week @ 2024-05-09 525/week @ 2024-05-16 455/week @ 2024-05-23 331/week @ 2024-05-30 384/week @ 2024-06-06 313/week @ 2024-06-13 450/week @ 2024-06-20 311/week @ 2024-06-27 275/week @ 2024-07-04 455/week @ 2024-07-11 516/week @ 2024-07-18

1,646 downloads per month
Used in 28 crates (11 directly)

MIT license

30KB
549 lines

boxcar

Crate Github Docs

A concurrent, append-only vector.

The vector provided by this crate suports concurrent get and push operations. All operations are lock-free.

Examples

Appending an element to a vector and retrieving it:

let vec = boxcar::Vec::new();
vec.push(42);
assert_eq!(vec[0], 42);

The vector can be shared across threads with an Arc:

use std::sync::Arc;

fn main() {
    let vec = Arc::new(boxcar::Vec::new());

    // spawn 6 threads that append to the vec
    let threads = (0..6)
        .map(|i| {
            let vec = vec.clone();

            std::thread::spawn(move || {
                vec.push(i); // push through `&Vec`
            })
        })
        .collect::<Vec<_>>();

    // wait for the threads to finish
    for thread in threads {
        thread.join().unwrap();
    }

    for i in 0..6 {
        assert!(vec.iter().any(|(_, &x)| x == i));
    }
}

Elements can be mutated through fine-grained locking:

use std::sync::{Mutex, Arc};

fn main() {
    let vec = Arc::new(boxcar::Vec::new());

    // insert an element
    vec.push(Mutex::new(1));

    let thread = std::thread::spawn({
        let vec = vec.clone();
        move || {
            // mutate through the mutex
            *vec[0].lock().unwrap() += 1;
        }
    });

    thread.join().unwrap();

    let x = vec[0].lock().unwrap();
    assert_eq!(*x, 2);
}

No runtime deps