Set unsync
Published 330d ago
ayebear
Using the dark arts of unsafe rust, we can cast immutable references to mutable pointers, and bypass the need for any slow "safe" Sync objects such as mutexes.
use rayon::prelude::*;
const SIZE: usize = 1000;
// set a vec/array/slice unsafely across threads without needing any slow syncing
unsafe fn set_unsync<T>(vec: &[T], idx: usize, val: T) {
let start = vec.as_ptr() as *mut T;
*start.add(idx) = val
}
fn main() {
let array = [0; SIZE];
(0..SIZE).into_par_iter().for_each(|n| {
// this could be any index
let i = SIZE - n - 1;
// only need immutable reference to mutate!
unsafe {
set_unsync(&array, i, n);
}
});
println!("{array:?}");
}
fastunsyncunsafesafethreadsmultithreading
Please login or sign up to comment and collaborate