Systems Advanced
17 Threads
std::thread runs work on OS threads. spawn returns a handle; join blocks until the thread finishes and hands back its return value. move captures owned data into the closure.
In parallel_sum, split the vec in half, sum each half on its own thread, and add the two results.
Hints
nums.split_at(mid)gives two slices;.to_vec()each so the threads own their data.- Join both handles and add:
h1.join().unwrap() + h2.join().unwrap().
Reveal solution
use std::thread;
fn parallel_sum(nums: Vec<i64>) -> i64 {
let mid = nums.len() / 2;
let (left, right) = nums.split_at(mid);
let left = left.to_vec();
let right = right.to_vec();
let h1 = thread::spawn(move || left.iter().sum::<i64>());
let h2 = thread::spawn(move || right.iter().sum::<i64>());
h1.join().unwrap() + h2.join().unwrap()
}