Sub topic 2
Spawning threads and joining them
This chapter covers std::thread::spawn, the JoinHandle it returns, and join, which waits for a thread and collects its result. It assumes you know Rust ownership and borrowing, closures, Result and unwrap, and basic traits and generics. You should also be able to build and run programs with cargo. The move keyword on closures gets its own chapter, so here it appears only where the compiler requires it.
What spawn does
std::thread::spawn asks the operating system for a new thread and starts running a closure on it. Rust threads are OS threads, with a one-to-one mapping. The scheduler decides when each one runs, and on a multicore machine several can run at the same moment.
The signature is worth reading closely:
pub fn spawn<F, T>(f: F) -> JoinHandle<T>
where
F: FnOnce() -> T + Send + 'static,
T: Send + 'static,Each part of it has a consequence:
F: FnOnce() -> Tmeans the closure runs exactly once and may consume what it captured.Tis whatever the closure returns. It becomes the result you can retrieve later.Sendmeans the closure and the return value must be safe to move to another thread. The Send and Sync chapter covers this rule.'staticmeans the closure cannot hold references to local variables of the spawning function. The new thread may outlive that function, and the compiler cannot prove otherwise.
spawn returns a JoinHandle<T> immediately. The spawning thread keeps running and does not wait for the new one.
Joining: waiting for a result
JoinHandle::join blocks the calling thread until the spawned thread finishes. It then returns the closure's return value wrapped in a Result.
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 type of handle is JoinHandle<u32>, and join returns Result<u32, Box<dyn Any + Send>>. The Err case happens only if the thread panicked. The panics chapter covers how to inspect that error. For now, unwrap is acceptable because it turns a worker panic into a panic in the caller.
Three properties of join matter in practice:
- It takes
self, so it consumes the handle. You can join a thread only once. - It blocks. If the thread never finishes,
joinnever returns. - It establishes ordering. Everything the spawned thread did happens before
joinreturns, so you can safely use its results.
The following diagram shows the sequence of events.
Running several threads
A common pattern is to spawn several threads, keep the handles in a Vec, and join them all afterward. Spawn every thread first and join afterward. If you join inside the spawning loop, each thread finishes before the next starts, and you lose the parallelism.
use std::thread;
fn main() {
let mut handles = Vec::new();
for id in 0..4u64 {
handles.push(thread::spawn(move || {
let sum: u64 = (1..=id * 1000).sum();
(id, sum)
}));
}
for h in handles {
let (id, sum) = h.join().unwrap();
println!("thread {id}: sum = {sum}");
}
}The closure uses move because it reads id, which belongs to the loop body. Without move the closure would borrow id, which conflicts with the 'static bound. The next chapter explains this error in detail.
The output is always in the order thread 0 to thread 3. That order comes from the join loop, which visits handles in the order you stored them. The threads themselves may finish in any order. If a thread finishes early, its result waits inside the handle until you call join. Joining in spawn order is therefore a simple way to get deterministic output from nondeterministic work.
Joining a slow thread first does not slow the others down. They keep running while you wait. The total wait is roughly the time of the slowest thread, not the sum.
What happens if you do not join
Dropping a JoinHandle does not stop or kill the thread. It detaches the thread, and the thread keeps running on its own. But when main returns, the process exits, and any threads still running are terminated without ceremony.
use std::thread;
use std::time::Duration;
fn main() {
thread::spawn(|| {
thread::sleep(Duration::from_millis(200));
println!("worker finished");
});
println!("main exits");
}This program prints main exits. It almost certainly never prints worker finished, because the process ends after about a microsecond of work in main. The thread is cut off mid-sleep, with no destructors run on its stack.
Do not use thread::sleep in main as a substitute for join. A sleep guesses how long the work takes. Too short and the work is lost, and too long and you waste time. join waits exactly as long as needed.
Detaching is still useful. A background thread that logs or monitors for the entire life of the process has no result to wait for, and it can simply be dropped. Choose this deliberately, knowing that the thread dies when the process does.
Checking without blocking
JoinHandle::is_finished returns true once the thread's closure has returned, without blocking. It is useful for polling, such as updating a progress display while waiting.
use std::thread;
use std::time::Duration;
fn main() {
let handle = thread::spawn(|| {
thread::sleep(Duration::from_millis(100));
"done"
});
while !handle.is_finished() {
println!("still working...");
thread::sleep(Duration::from_millis(30));
}
println!("{}", handle.join().unwrap());
}The number of still working... lines depends on timing, usually three or four. Calling join after is_finished returns true is still required to get the value, but it will not block.
Naming threads and setting the stack size
thread::spawn uses default settings. For more control, use thread::Builder. It lets you name the thread and set its stack size. Names appear in panic messages and in debuggers, which makes failures much easier to trace.
use std::thread;
fn main() -> std::io::Result<()> {
let handle = thread::Builder::new()
.name("summer".to_string())
.stack_size(256 * 1024)
.spawn(|| {
let name = thread::current().name().map(str::to_owned);
println!("running in {name:?}");
42
})?;
let value = handle.join().unwrap();
println!("value = {value}");
Ok(())
}This prints running in Some("summer") and then value = 42. Two details are worth noting.
Builder::spawnreturnsio::Result<JoinHandle<T>>. Creating a thread can fail, for example when the OS has hit a thread limit. Plainthread::spawnpanics in that case, while the builder lets you handle the error.thread::current()returns a handle to the running thread.name()returnsOption<&str>, because unnamed threads have no name. The main thread is named"main".
The default stack size for spawned threads is 2 MiB on most platforms. Deep recursion or large stack arrays inside a thread can overflow it, and that aborts the whole process rather than panicking. Raise the size with the builder if you need to. Do not raise it for no reason, because each thread reserves that much address space.
Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Joining inside the spawn loop | Work runs one thread at a time | Collect handles first, then join in a second loop |
| Forgetting to join | Output or side effects missing, varying from run to run | Keep the handle and call `join` before `main` returns |
| Using `sleep` to wait | Flaky timing, or wasted time | Use `join` |
| Borrowing a local in the closure | Error that the closure may outlive the borrowed value | Add `move`, or use scoped threads (a later chapter) |
| Assuming output order | Different order on each run | Order results by joining handles in a known sequence |
| Spawning thousands of OS threads | Spawn failure, or high memory use | Use a fixed number of workers, as in the worker pool chapter |
Summary of the model
spawnstarts a thread and returns aJoinHandle<T>at once.- The closure must be
Send + 'static, and its return value must also beSend + 'static. joinconsumes the handle, blocks until the thread ends, and returnsResult<T, _>. TheErrcase means the thread panicked.- Dropping a handle detaches the thread, and process exit kills it.
is_finishedpolls without blocking, andBuilderadds a name, a stack size, and a recoverable spawn error.
Exercise
This program is meant to print the sum of two ranges computed in parallel, but it often prints nothing from the threads. What is wrong, and how do you fix it? use std::thread; fn main() { thread::spawn(|| println!("low = {}", (1..=100).sum::<u32>())); thread::spawn(|| println!("high = {}", (101..=200).sum::<u32>())); }
Show answer
Both handles are dropped immediately, so the threads are detached, and main returns right away. The process exits before the threads are guaranteed to run. Store the handles, for example let a = thread::spawn(...); let b = thread::spawn(...);, then call a.join().unwrap(); and b.join().unwrap(); before main ends. A better design returns the sums from the closures and prints them in main after joining, which also gives a fixed output order.
Exercise
You spawn eight threads that each return a u32. Write the shape of the code that collects all eight results into a Vec<u32> while letting the threads run in parallel.
Show answer
Spawn first, then join. For example: let handles: Vec<_> = (0..8u32).map(|i| thread::spawn(move || i * i)).collect(); followed by let results: Vec<u32> = handles.into_iter().map(|h| h.join().unwrap()).collect();. The first statement starts all eight threads before any join happens. The second blocks on each handle in order, so results is in spawn order.