Sub topic 1
Threads and move closures: the starting point
This chapter covers the thread and closure mechanics that every later chapter relies on. You will see what thread::spawn requires of its closure, why the compiler insists on move, and how data and results move between threads. By the end you will also see why moving data is not enough once several threads need the same value.
Prerequisites
This chapter assumes you already know the following:
- Rust ownership, borrowing and lifetimes at a basic level, including what
'staticmeans. - Closures and the
movekeyword. - That
std::thread::spawnreturns aJoinHandle. - How
Result,unwrapand pattern matching work.
What thread::spawn does
thread::spawn starts a new operating system thread and runs a closure on it. It returns a JoinHandle<T>, where T is the closure's return type. Calling join() on the handle blocks the calling thread until the spawned thread finishes. It returns a Result<T, Box<dyn Any + Send>>.
use std::thread;
fn main() {
let handle = thread::spawn(|| {
println!("hello from the spawned thread");
21 * 2
});
let answer = handle.join().unwrap();
println!("answer = {answer}");
}The closure runs concurrently with main. The order of the two println! calls is not guaranteed in general. Here join forces the second one to come last, because main cannot print until the thread has finished.
The signature of spawn explains most of what follows:
pub fn spawn<F, T>(f: F) -> JoinHandle<T>
where
F: FnOnce() -> T + Send + 'static,
T: Send + 'static,Each bound on F has a purpose:
FnOncemeans the closure is called exactly once, so it may consume what it captured.Sendmeans the closure may be moved to another thread. Later chapters coverSendin detail.'staticmeans the closure cannot hold references that could expire before the thread ends.
The same Send + 'static bounds apply to the return value T.
Why a borrowing closure is rejected
The 'static bound is the reason borrowing fails. The compiler cannot know how long the spawned thread will live. It might outlive the function that created it. A reference to a local variable could then dangle.
use std::thread;
fn main() {
let names = vec![String::from("a"), String::from("b")];
// Does not compile: the closure may outlive `main`, but it borrows `names`.
let handle = thread::spawn(|| {
println!("{:?}", names);
});
handle.join().unwrap();
}The compiler reports error E0373: "closure may outlive the current function, but it borrows names". It suggests using the move keyword.
The code above calls join before names goes out of scope, so it would be safe in practice. The compiler does not reason about that. The signature of spawn promises nothing about when the thread ends, so the check is conservative. Scoped threads, covered in a later chapter, remove this restriction by guaranteeing the thread ends first.
Moving ownership into the thread
A move closure takes ownership of every variable it uses. The thread then owns its data, so nothing can dangle.
use std::thread;
fn main() {
let names = vec![String::from("a"), String::from("b")];
let handle = thread::spawn(move || {
println!("{:?}", names);
});
handle.join().unwrap();
// `names` was moved into the closure, so it cannot be used here.
}After the move, the main thread can no longer use names. Using it would be a compile error ("borrow of moved value"). This is ownership working as usual, now applied across threads. The thread is the only owner, so no other thread can touch the vector.
Types that implement Copy, such as integers, are copied into the closure instead. The original stays usable:
use std::thread;
fn main() {
let n = 5;
let handle = thread::spawn(move || n + 1);
println!("main still sees n = {n}");
println!("thread returned {}", handle.join().unwrap());
}Even with Copy types, move is still required. Without it the closure would capture n by reference, and the 'static check would fail.
Giving each thread its own data
A common pattern is to build one value per thread inside a loop and move it in. Each thread owns an independent value, so no coordination is needed.
use std::thread;
fn main() {
let handles: Vec<thread::JoinHandle<usize>> = (0..3)
.map(|i| {
let text = format!("task-{i}");
thread::spawn(move || text.len() + i)
})
.collect();
for handle in handles {
println!("{}", handle.join().unwrap());
}
}This prints 6, 7 and 8. The handles are stored in a Vec and joined in order. Collecting all the handles before joining any of them matters. If you spawned and joined inside the same loop iteration, the threads would run one after another instead of in parallel.
If several threads need a copy of the same data, clone it before the move and give each thread its own clone:
use std::thread;
fn main() {
let config = String::from("verbose");
let mut handles = Vec::new();
for id in 0..3 {
let config = config.clone(); // shadows the outer name, one clone per thread
handles.push(thread::spawn(move || {
format!("worker {id} uses {config}")
}));
}
for handle in handles {
println!("{}", handle.join().unwrap());
}
}The inner let config = config.clone(); shadows the outer variable. The closure then moves the clone, and the original stays in main. You will see this shadowing idiom again with Arc::clone.
Join, panics and detached threads
join returns a Result because the thread might have panicked. A panic in a spawned thread does not take down the whole program. It unwinds that thread only, and the panic payload comes back as the Err value.
use std::thread;
fn main() {
let result = thread::spawn(|| -> i32 {
panic!("boom");
})
.join();
println!("thread panicked: {}", result.is_err());
}The panic message still prints to standard error. The program then prints thread panicked: true. Calling unwrap() on that Err would panic the main thread in turn. Whether that is what you want depends on how critical the worker is.
If you drop a JoinHandle without calling join, the thread is detached. It keeps running, but nobody can wait for it or read its result. When main returns, the process exits and any detached threads are stopped mid-work. A spawned thread that is never joined may therefore never finish its job.
The limit of move
move solves the lifetime problem by giving one thread exclusive ownership. That raises the question this tutorial is about. What if two threads both need to read and modify the same value?
use std::thread;
fn main() {
let mut count = 0;
let first = thread::spawn(move || {
count += 1;
count
});
// `count` is an i32, so it was copied. `first` changed its own copy.
println!("main sees {count}");
println!("thread saw {}", first.join().unwrap());
}This compiles, but it does not do what a beginner might hope. The thread incremented its own copy, and main still sees 0. Moving or copying gives each thread private data. It cannot give two threads one shared, changing value. For that you need shared ownership, which is Arc. You also need controlled mutation, which is Mutex. The next chapters build both.
Common errors at a glance
| Symptom | Cause | Fix |
|---|---|---|
| E0373: closure may outlive the current function | The closure borrows a local variable | Add `move`, or use a scoped thread |
| "borrow of moved value" after spawning | The value now belongs to the thread | Clone before the `move`, or restructure |
| Output missing or truncated | `main` returned before the thread finished | Keep the handle and call `join` |
| Threads run one after another | `join` called inside the spawning loop | Collect handles first, then join |
| Counter changes are invisible to `main` | A `Copy` value was copied into the closure | Use shared state (next chapters) |
Exercise
The following code fails to compile. Name the error's cause and give a fix that keeps main able to print label afterward. let label = String::from("job"); let h = thread::spawn(|| println!("{label}")); h.join().unwrap(); println!("{label}");
Show answer
The closure borrows label, but thread::spawn requires a 'static closure, so the compiler reports E0373. Adding move alone would let the thread compile, but then the final println! in main would use a moved value. The fix is to clone first and move the clone: let label_for_thread = label.clone(); let h = thread::spawn(move || println!("{label_for_thread}"));. The original label stays usable in main.
Exercise
A program spawns a worker with thread::spawn(|| expensive_job());, drops the returned handle, and then returns from main. The job's output sometimes never appears. Why, and what changes it?
Show answer
Dropping the JoinHandle detaches the thread, and returning from main ends the process, which stops the detached thread wherever it is. Keep the handle and call handle.join().unwrap() before main returns, so the program waits for the job to finish.