Sum a large slice on several threads with thread::scope, borrowing the slice
Write parallel_sum, which splits data into about parts pieces, sums each piece on its own thread and returns the total. Then explain why the same function written with thread::spawn would have needed move and owned ('static) data.
Requirements:
- The threads borrow
data: noclone, noto_vec, noArc. parts >= 1; the length ofdataneed not divide evenly; an empty slice gives0.mainstays as it is and prints500000500000and then1000000.
use std::thread;
fn parallel_sum(data: &[u64], parts: usize) -> u64 {
// your code here
}
fn main() {
let numbers: Vec<u64> = (1..=1_000_000).collect();
println!("{}", parallel_sum(&numbers, 4));
println!("{}", numbers.len());
}Write the implementation.
thread::scope joins all its threads before returning, so s.spawn closures may borrow data. Split it with chunks, sum each chunk in a scoped thread, add the results. thread::spawn demands 'static, forcing move or Arc.
- Wrapping the data in
Arcor cloning it for threads that are joined inside the same function - Calling
thread::spawninstead ofs.spawninside the scope, which still demands'static - Expecting a
joinright afterthread::spawnto let the closure borrow local data
- What happens to
thread::scopewhen one of its threads panics and was not joined by hand? - How would you let each scoped thread double the numbers of its own piece in place?
thread::scope gives the compiler a guarantee it cannot derive on its own: every thread started with s.spawn finishes before the scope returns. Since the threads cannot outlive the function, their closures may hold ordinary references to data:
use std::thread;
fn parallel_sum(data: &[u64], parts: usize) -> u64 {
let chunk = data.len().div_ceil(parts).max(1);
thread::scope(|s| {
let handles: Vec<_> = data
.chunks(chunk)
.map(|c| s.spawn(|| c.iter().sum::<u64>()))
.collect();
handles.into_iter().map(|h| h.join().unwrap()).sum()
})
}
fn main() {
let numbers: Vec<u64> = (1..=1_000_000).collect();
println!("{}", parallel_sum(&numbers, 4)); // 500000500000
println!("{}", parallel_sum(&numbers[..10], 3)); // 55
println!("{}", parallel_sum(&[], 4)); // 0
println!("{}", numbers.len()); // 1000000
}div_ceil rounds the chunk size up, so there are at most parts chunks and the last may be shorter. .max(1) covers the empty slice: chunks(0) panics, while chunks(1) on an empty slice simply yields nothing and the sum is 0. The handles are collected into a Vec first and joined afterwards: a lazy map with join inside would run the threads one at a time.
With thread::spawn the same function does not compile: spawn requires a 'static closure, because the thread may outlive the calling function, and the borrowed data may not. The compiler answers error[E0521]: borrowed data escapes outside of function, and the join below changes nothing — it looks at the signature of spawn. You would have to move owned data into each thread (a to_vec of the chunk) or share it through an Arc<Vec<u64>>.