I am learning Rust and am now taking a look at threads. I am trying to convert the following snippet into a parallelized execution:
fn main() {
let mut data: Vec<usize> = (1..22).collect();
for d in &mut data {
*d *= 99;
}
}
Since the processing of each element is completely independent from the others, this should be easy to parallelize. So I wrote the following code which splits the vector into N_THREADS
parts and then gives each part to a thread to do the processing:
use std::thread;
const N_THREADS: usize = 8;
const N_ELEMENTS: usize = 2*N_THREADS;
fn main() {
let mut data: Vec<usize> = (1..N_ELEMENTS).collect();
let mut threads = vec![];
for n_thread in 0..N_THREADS {
let thread_fn = move || {
for d in &mut data[n_thread*(N_ELEMENTS/N_THREADS)..(n_thread+1)*(N_ELEMENTS/N_THREADS)] {
*d *= 99
}
};
let thread_handle = thread::spawn(thread_fn);
threads.push(thread_handle);
}
// Now wait for the threads to finish.
for t in threads {
t.join().unwrap();
} // I need each `t` to return the ownership of its respective piece of `data` here!
do_something_else(data);
}
How can I get the ownership of data
back after all the threads have finished, so then I can do_something_else(data)
?