expression
Scoped threads with disjoint mutable slices
Split a mutable slice into nonoverlapping regions before spawning workers. Each worker exclusively borrows its region, so no lock is needed for these independent updates. The parent accesses the whole array only after the scope ends. Expected stdout (not executed): [11, 12, 6, 8] Common mistake: Trying to give two workers simultaneous mutable references to overlapping data.
Formal Syntax & Structure
rust syntaxrust
slice.split_at_mut(mid); thread::scopeWorking Example
Example Snippetrust
fn main() { let mut data = [1, 2, 3, 4]; let (left, right) = data.split_at_mut(2); std::thread::scope(|s| { s.spawn(move || { for n in left { *n += 10; } }); s.spawn(move || { for n in right { *n *= 2; } }); }); println!("{:?}", data);}