Threads
std::thread::spawn starts an OS thread that runs a closure. The thread owns the closure's captures, which must be Send, and join waits for it to finish.
Detailed Explanation
thread::spawn(|| { ... }) asks the OS for a new thread. The closure runs in parallel with the caller. It must be 'static and Send: everything it captures has to be safe to move to another thread and must not dangle when the spawning stack frame returns. That is why you move the closure and why a mere &local will not compile.
JoinHandle::join waits and returns Result<T> of the closure's return value. If the thread panicked, join gives Err with the panic payload. Dropping a JoinHandle detaches the thread: it keeps running, and you cannot collect its result. Detached threads that outlive main are killed when the process exits.
thread::scope (Rust 1.63+) lets threads borrow from the parent stack. The scope waits for all spawned threads before it ends, so the 'static requirement relaxes. Use a scope when the worker only needs a slice that the parent already owns and you do not want to clone or Arc it.
Threads are expensive compared to async tasks. Each has a stack (about 2 MiB by default on many platforms) and a kernel object. A few dozen workers is normal. Tens of thousands of blocked OS threads is a mistake; that workload is why Tokio exists. available_parallelism is the hint for "how many CPU-bound workers".
Sharing is explicit. A value moved into one thread is gone from the other. Two threads that must both see a value use Arc. Two threads that must both write use Arc<Mutex<T>> or a channel. The compiler rejects a shared &mut across spawn.
When you spawn a thread: CPU-bound work, blocking syscalls you do not want on an async runtime, or isolation of a panic. When you use async: many waiting I/O tasks. When you use thread::scope: short parallel borrows of existing data.
Code Examples
use std::thread;
fn main() {
let name = String::from("ada");
let handle = thread::spawn(move || {
format!("hello {name}")
});
println!("{}", handle.join().unwrap()); // prints: hello ada
}Common Gotchas
Captured references must be `'static` unless you use `scope`
The thread may outlive the frame. Clone, `Arc`, or `thread::scope`.
Dropping a `JoinHandle` detaches
A background thread you forgot to `join` can still be running when you thought the work was done.
A panic in a thread does not panic `main`
`join` returns `Err`. Unwrapping it is how you surface the panic.
`move` is almost always required
Without it the closure tries to borrow, and `spawn` rejects that borrow.