Home > other >  Parallel write to array with a unique indices array
Parallel write to array with a unique indices array

Time:01-25

This question is analogical to Parallel write to array with an indices array except that I guarantee the indices to be unique.

let indices = [1, 4, 7, 8];
let mut arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

indices.iter_par().for_each(|x| {
    arr[x] = some_function(x);
});

Is there a way to achieve this in Rayon? Perhaps I should somehow use unsafe, because obviously borrow checker can't verify uniqueness of indices.

CodePudding user response:

You can certainly do it with unsafe, for example by sending a pointer to the threads:

let indices = [1, 4, 7, 8];
let mut arr = [1u32, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let arr_ptr = arr.as_mut_ptr() as usize;

indices.into_par_iter().for_each(|x| {
    let arr_ptr = arr_ptr as *mut u32;
    // safety:
    // * `indices` must be unique and point inside `arr`
    // * `place` must not leak outside the closure
    // * no element in `indices` may be modified by some other thread
    let place = unsafe { &mut *arr_ptr.add(x) };
    *place = some_function(x);
});

But I'd keep that kind of thing as a last resort - once you introduce ad-hoc unsafe like this in your code, you never know when you'll make a misstep and make your code vulnerable to random crashes and corruptions.

  •  Tags:  
  • Related