9 releases

0.2.8 Dec 29, 2024
0.2.7 Nov 7, 2024
0.2.6 Oct 3, 2024
0.2.5 May 1, 2024
0.1.0 Mar 13, 2022

#227 in Concurrency

Download history 3001/week @ 2024-09-22 3497/week @ 2024-09-29 3407/week @ 2024-10-06 3183/week @ 2024-10-13 3544/week @ 2024-10-20 3996/week @ 2024-10-27 4271/week @ 2024-11-03 4583/week @ 2024-11-10 6356/week @ 2024-11-17 6035/week @ 2024-11-24 6790/week @ 2024-12-01 9268/week @ 2024-12-08 7831/week @ 2024-12-15 4250/week @ 2024-12-22 5671/week @ 2024-12-29 9526/week @ 2025-01-05

27,949 downloads per month
Used in 60 crates (16 directly)

MIT license

35KB
607 lines

boxcar

crates.io github docs.rs

A concurrent, append-only vector.

The vector provided by this crate supports lock-free get and push operations.

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