43 releases (18 breaking)

new 0.19.6 Jun 19, 2024
0.19.0 May 31, 2024
0.18.2 Mar 15, 2024
0.14.0 Dec 29, 2023
0.11.2 Oct 27, 2023

#208 in Concurrency

Download history 77/week @ 2024-02-26 17/week @ 2024-03-04 400/week @ 2024-03-11 46/week @ 2024-03-18 38/week @ 2024-04-01 5/week @ 2024-04-08 9/week @ 2024-04-15 9/week @ 2024-05-20 445/week @ 2024-05-27 365/week @ 2024-06-03 326/week @ 2024-06-10

1,145 downloads per month
Used in 3 crates

MIT/Apache

60KB
1K SLoC

pi_arr

Crate Github Docs

Multi thread safe array structure, auto-expansion array. All operations are lock-free.

Examples

set an element to a arr and retrieving it:

let arr = pi_arr::Arr::new();
arr.set(0, 42);
assert_eq!(arr[0], 42);

The arr can be shared across threads with an Arc:

use std::sync::Arc;

fn main() {
    let arr = Arc::new(pi_arr::Arr::new());

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

            std::thread::spawn(move || {
                arr.set(i, i);
            })
        })
        .collect::<Vec<_>>();

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

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

Elements can be mutated through fine-grained locking:

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

fn main() {
    let arr = Arc::new(pi_arr::Arr::new());

    // insert an element
    arr.set(0, Mutex::new(1));

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

    thread.join().unwrap();

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

Dependencies

~170KB