Sub topic 2
Spawning threads and joining them
This chapter assumes you know Rust ownership and borrowing, closures, Result and unwrap, and how to build programs with cargo. It covers how to start a thread and how to wait for its result. Moving data into threads comes in the next chapter.
What `thread::spawn` does
std::thread::spawn takes a closure and starts a new operating system thread that runs it. The call returns right away with a JoinHandle<T>, where T is the closure's return type. The new thread runs on its own schedule, so the order of output between threads is not fixed.
The handle is your only link to the thread. Calling join on it blocks the current thread until the spawned thread finishes. It returns Result<T, _>, so the closure's value comes back to you.
use std::thread;
fn main() {
let handle = thread::spawn(|| (1..=5).sum::<u32>());
let total = handle.join().unwrap();
println!("total = {total}");
}This prints total = 15. The spawned thread computes the sum. join waits for it and hands the number back inside Ok.
The timeline of a spawn and join
The diagram shows the two threads. The main thread keeps running after spawn, then blocks at join until the child is done.
What happens if you do not join
If main returns, the whole process exits. Any thread still running is stopped, even if it has not finished its work. A dropped JoinHandle does not stop its thread. It only detaches it, so you lose the ability to wait for it or read its result.
use std::thread;
use std::time::Duration;
fn main() {
let handle = thread::spawn(|| {
thread::sleep(Duration::from_millis(100));
println!("child finished");
});
println!("main is done waiting? no, joining now");
handle.join().unwrap();
}Remove the join line and child finished will usually never print, because main ends first.
Spawning several threads
A common pattern is to start many threads, store their handles in a Vec, and join them all afterwards. Start every thread before joining any of them. If you join inside the spawning loop, each thread finishes before the next one starts, and you get no parallelism.
use std::thread;
fn main() {
let mut handles = Vec::new();
for id in 0..4 {
handles.push(thread::spawn(move || id * 10));
}
let results: Vec<i32> = handles
.into_iter()
.map(|h| h.join().unwrap())
.collect();
println!("{results:?}");
}This prints [0, 10, 20, 30]. Joining in handle order gives results in a predictable order, even though the threads may finish in any order.
Common mistakes
- Joining inside the spawn loop. This runs the threads one at a time. Collect handles first, then join.
- Assuming output order. Two threads that both print can interleave in any order. Only
joinestablishes that one thread has finished. - Ignoring the
Result.joinreturnsErrif the thread panicked. Callingunwrapturns that into a panic in the joining thread. A later chapter shows how to handle it more carefully. - Expecting a detached thread to finish. A thread you never join can be cut off when
mainreturns.
Exercise
A program spawns three threads in a loop and calls join().unwrap() on each handle right after spawning it, inside the same loop iteration. Each thread sleeps for one second. About how long does the loop take, and how would you change it so the three sleeps overlap?
Show answer
It takes about three seconds, because each join waits for one thread to finish before the next thread is spawned. Push each handle into a Vec inside the loop, then join all the handles in a second loop. The three sleeps then run at the same time and the total is about one second.