Sub topic 3
Why thread closures use move
This chapter assumes you know ownership and borrowing, how closures capture variables, and how to use Result and unwrap. It also assumes you can run programs with cargo. It covers why thread::spawn almost always needs move, and what that does to your variables.
The problem: a thread can outlive its caller
thread::spawn starts a new OS thread and returns immediately. The new thread may keep running after the function that spawned it has returned. Any local variable it borrowed would then be gone.
The signature of spawn encodes this. The closure must be 'static, which means it cannot hold references to data that lives on the spawning thread's stack. A closure that only borrows a local String or Vec is rejected with error E0373, "closure may outlive the current function, but it borrows name". The compiler suggests adding move.
What move does
By default a closure captures each variable in the weakest way its body needs. If the body only reads name, the closure borrows it. Putting move before the closure changes this. The closure takes ownership of every variable it uses.
use std::thread;
fn main() {
let name = String::from("worker");
let handle = thread::spawn(move || {
println!("hello from {name}");
});
handle.join().unwrap();
}The String now belongs to the closure, and the closure belongs to the new thread. Nothing borrowed from main remains, so the 'static requirement is met.
Moved values are gone from the caller
After a move, the original variable is unusable in the spawning thread, for any type that is not Copy. Using name after the spawn call above fails with "borrow of moved value".
Types that implement Copy, such as i32, bool, and f64, are copied into the closure. The original stays usable, and the two copies are independent. Changing one does not change the other.
Keeping a copy: clone first
If both threads need the data, make a separate copy before the move. Cloning a value gives the thread its own.
use std::thread;
fn main() {
let data = vec![1, 2, 3];
let for_thread = data.clone();
let handle = thread::spawn(move || for_thread.iter().sum::<i32>());
println!("main still has {data:?}");
println!("thread sum = {}", handle.join().unwrap());
}Only for_thread moves. data stays in main. Cloning a large collection costs time and memory. When the data is big or must be shared, you will want Arc instead, which a later chapter covers.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| E0373, closure may outlive the current function | The closure borrows a local variable | Add `move` |
| Borrow of moved value | You used a variable after moving it into the closure | Clone before the move, or stop using it |
| Moved in a previous iteration of loop | You moved the same variable into a closure on every pass | Create a fresh clone inside the loop body |
The loop case is easy to hit. If you spawn several threads in a for loop, each closure needs its own value. Clone inside the loop, then move that clone.
When you can skip move
move is needed because spawn demands 'static. Scoped threads, covered later, guarantee that every thread finishes before the scope ends. They can borrow local data without move, and you do not need to give the data up.
Exercise
A program creates let log = String::from("start");, spawns a thread with move || println!("{log}"), and then calls println!("{log}") in main. Why does it fail to compile, and what is one way to fix it?
Show answer
The move closure took ownership of log, so main can no longer use it. One fix is to clone first, with let log_for_thread = log.clone();, and move the clone into the closure. main keeps the original log.