par_slice
ParSlice is a utility crate to allow easier access to data in parallel when data races are avoided at compile time or through other means but the compiler has no way to know.
Basic usage
On a basic level, using this crate is easy:
use *;
use scope;
// Let's create a slice accessible in parallel with 6 values initialized to 0.
let slice = with_value;
// Let's update even indexes to 42 in one thread and odd indexes
// to 69 in another thread.
scope;
// Let's convert the parallel slice into a boxed slice.
let boxed_slice = slice.into;
assert_eq!;
At the same time, though, it is extremely easy to geneate undefined behavior:
use *;
use scope;
// Let's create a slice accessible in parallel with 6 values initialized to 0.
let slice = with_value;
// Let's update even indexes to 42 in one thread and odd indexes
// to 69 in another thread.
// This is UB as the two threads may hold a mutable reference to the same element,
// thus violating Rust's aliasing rules.
scope;
// Let's convert the parallel slice into a boxed slice.
let boxed_slice = slice.into;
assert_eq!;
Access Paradigms
In order to reduce the risk of producing UB, this crate offers 3 levels of access, each with their invariants:
PointerIndexandPointerChunkIndexallow access through pointers, allowing the maximum safety at the cost of ergonomics: creating the pointers is always safe, but dereferencing them while avoiding data races and abiding by Rust's aliasing rules is up to the user.UnsafeNoRefIndexandUnsafeNoRefChunkIndexallow access through setters and getters. This allows the user to not think about reference aliasing and lifetimes (as no references are ever created) and to only handle the possibility of data races.UnsafeIndexandUnsafeChunkIndexallow access through references, allowing the maximum ergonomics at the cost of safety: using the references is always safe, but the user must guarantee that Rust's aliasing rules are always respected (under penalty of [undefined behavior]).
Real-World Use Case
But why should I want this?
This is particularily useful in Breadth-First visits situations, especially on data structures like graphs, when we want to be able to access in parallel arbitrary data but with the BFS guarantee of not visiting the same node twice.