Let work run independently.
Transfer ownership into a thread and join its result.
01 Understand the contract
std::thread::spawn runs a closure on another operating-system thread. Spawned closures generally need owned or static data because the new thread may outlive the caller’s current stack frame. A move closure can transfer a vector into the thread. join waits for termination and returns a Result because the thread may panic. Thread scheduling is nondeterministic, so do not depend on print ordering. For borrowed work that must finish before a scope exits, scoped threads provide a useful alternative.
02 Make it concrete
This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.
use std::thread;
fn main() {
let values = vec![2, 4, 6];
let worker = thread::spawn(move || values.into_iter().sum::<i32>());
let total = worker.join().expect("worker completed");
println!("total={total}");
}total=12
- 1
move transfers the vector into the closure.
- 2
The worker owns the values it consumes.
- 3
join returns the final sum and synchronizes completion.
cargo run -p lesson_threads03 Mind the boundary
04 Your next build
Use thread::scope to sum two borrowed halves, then combine the results.
Reveal one possible solution +
use std::thread;
fn main() {
let values = [1, 2, 3, 4];
let total = thread::scope(|scope| {
let a = scope.spawn(|| values[..2].iter().sum::<i32>());
let b = scope.spawn(|| values[2..].iter().sum::<i32>());
a.join().unwrap() + b.join().unwrap()
});
assert_eq!(total, 10);
}05 Check your reasoning
Does dropping a JoinHandle cancel the thread?
Understand it.
Then make it yours.
Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.