并行写入具有唯一索引数组的数组

Parallel write to array with a unique indices array

这个问题类比于 除了我保证索引是唯一的。

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);
});

有没有办法在人造丝中实现这一点?也许我应该以某种方式使用 unsafe,因为显然借用检查器无法验证索引的唯一性。

你当然可以用 unsafe 做到这一点,例如通过发送一个指向线程的指针:

// thin wrapper over pointer to make it Send/Sync
#[derive(Copy, Clone)]
struct Pointer(*mut u32);
unsafe impl Send for Pointer {}
unsafe impl Sync for Pointer {}

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

indices.into_par_iter().for_each(move |x| {
    // safety:
    // * `indices` must be unique and point inside `arr`
    // * `place` must not leak outside the closure
    // * no element of `array` that is in `indices` may be accessed by
    //   some other thread while this is running
    let place = unsafe { &mut *{arr_ptr}.0.add(x) };
    *place = some_function(x);
});

但我会保留那种东西,只作为最后的手段使用。一旦在您的代码库中像这样引入 ad-hoc unsafe,您永远不知道什么时候会犯错并使您的程序容易受到随机崩溃和损坏的影响。