Fastest multi-thread way to access array in Rust

43 views Asked by At

Consider the following code:

use rayon::prelude::*;

fn main() {
    let length = 100_000_000;
    let mut arr = vec![0; length];
    (0..length).into_par_iter().for_each(|i| {
        arr[i] = i;
    });
}

It is pretty clear that this code is thread-safe; the index where this program access the array is unique for every threads.

However, this produces an error saying:

cannot borrow arr as mutable, as it is a captured variable in a Fn closure

Is there some way to circumvent this? (I have heard of Mutex and things, but I'm not really sure.)

By the way, the task I'm working on right now is pretty resource-intensive, so I will appreciate if you could tell me the fastest way.

The algorithm is not very complicated, so I would like you to suggest potentially unsafe way if it exists (something like Rust's unsafe block).

Thank you!

0

There are 0 answers