Sub topic 3
Why thread closures use move
This chapter assumes you know Rust ownership and borrowing, how closures capture variables, and how to read a compiler error. The previous chapter showed thread::spawn and join. Here you will see why nearly every closure passed to spawn starts with move, and what to do when move causes problems of its own.
The problem: a thread can outlive its parent's stack frame
Start with a program that looks reasonable but does not compile. It is shown here to demonstrate the error.
use std::thread;
fn main() {
let v = vec![1, 2, 3];
// does not compile: the closure borrows `v`
let handle = thread::spawn(|| {
println!("{v:?}");
});
handle.join().unwrap();
}The compiler rejects it:
error[E0373]: closure may outlive the current function, but it borrows `v`,
which is owned by the current function
help: to force the closure to take ownership of `v` (and any other referenced
variables), use the `move` keywordThe closure only reads v, so Rust captures it by shared reference. That reference points into main's stack frame. The new thread runs independently, and Rust cannot know how long it will live. The thread might still be running after main returns and its locals are gone. A reference to freed memory is a dangling reference, and safe Rust does not allow one.
You and I can see that join is called before main ends. The compiler does not reason about that. It checks the signature of spawn.
What spawn demands
The signature of std::thread::spawn is:
pub fn spawn<F, T>(f: F) -> JoinHandle<T>
where
F: FnOnce() -> T + Send + 'static,
T: Send + 'static,Each bound has a job:
FnOnce() -> Tmeans the closure is called once and may consume what it captured.Sendmeans the closure can be moved to another thread. The next chapters cover this trait.'staticmeans the closure holds no references to data that could be freed before the thread ends. It may hold owned values, or references that live for the whole program, such as string literals.- The return type
Tmust also beSend + 'static, because the value travels back to whoever callsjoin.
A closure that borrows a local variable is not 'static. A closure that owns everything it uses is.
What move does
A closure normally captures each variable in the weakest way its body allows: by shared reference if it only reads, by mutable reference if it mutates, and by value if it consumes. The move keyword overrides that choice. Every captured variable is moved into the closure, whatever the body does with it.
use std::thread;
fn main() {
let names = vec![String::from("ada"), String::from("grace")];
let handle = thread::spawn(move || {
for name in &names {
println!("hello, {name}");
}
names.len()
});
let count = handle.join().unwrap();
println!("{count} names greeted");
}The body only borrows names, but move makes the closure own the vector. The closure has no references to main's frame, so it satisfies 'static.
Ownership transfers: the parent loses access
move is a real move. After the closure takes a non-Copy value, the parent can no longer use it.
use std::thread;
fn main() {
let message = String::from("sent to the thread");
let handle = thread::spawn(move || {
println!("{message}");
});
// println!("{message}"); // error[E0382]: borrow of moved value: `message`
handle.join().unwrap();
}If you uncomment the println!, the compiler reports a borrow of a moved value. This is the safety property working as designed. Once the data lives on another thread, the parent cannot touch it, so no two threads can race on it.
Copy types are copied, not moved
For types that implement Copy, such as integers, bool, and char, move copies the value. The parent keeps its own independent copy.
use std::thread;
fn main() {
let mut count = 0;
let handle = thread::spawn(move || {
count += 10;
count
});
println!("thread says {}", handle.join().unwrap());
println!("main still has {count}");
}This prints thread says 10 and main still has 0. The thread incremented its own copy. Programmers often expect the change to show up in the parent, and it never does. To share a changing value between threads you need Arc and Mutex, covered later in this tutorial.
Keeping a value: clone before you move
When both sides need the data, give the thread a clone. Use a clone with a new name or shadow the original inside a small block, so the closure captures the clone.
use std::thread;
fn main() {
let limit = 3;
let label = String::from("job");
let label_for_thread = label.clone();
let handle = thread::spawn(move || {
for i in 0..limit {
println!("{label_for_thread} {i}");
}
});
handle.join().unwrap();
println!("{label} is still usable, limit = {limit}");
}Here limit is copied and label_for_thread is moved. The original label stays in main. Cloning copies the data, so for large buffers it can be expensive. When many threads need read access to one large value, Arc shares it without copying, and you will use it later in this tutorial.
Spawning in a loop
A loop is where move most often causes surprises. The closure moves whatever it captures, and an iteration can move a value only once.
use std::thread;
fn main() {
let prefix = String::from("worker");
let mut handles = Vec::new();
for id in 0..3 {
let prefix = prefix.clone();
handles.push(thread::spawn(move || format!("{prefix}-{id}")));
}
for h in handles {
println!("{}", h.join().unwrap());
}
}Each iteration clones prefix into a new local with the same name, and the closure moves that clone. The loop variable id is an integer, so it is copied. If you delete the let prefix = prefix.clone(); line, the first iteration moves the original prefix and the second fails with "value moved into closure here, in previous iteration of loop".
Moving references and what move cannot fix
move moves the captured variable itself. If that variable is a reference, the reference is moved and the data it points to stays where it was. Moving a reference to a local does not make it 'static.
use std::thread;
fn main() {
let data = vec![1, 2, 3];
let r = &data;
// does not compile: `data` does not live long enough for 'static
let handle = thread::spawn(move || {
println!("{r:?}");
});
handle.join().unwrap();
}The error is now about lifetimes (borrowed value does not live long enough) rather than E0373. The fix is to move data itself, or to use scoped threads, which are covered in their own chapter. Scoped threads let closures borrow locals because the scope guarantees every thread finishes before the borrowed data goes away.
Common errors and what they mean
| Error | Cause | Typical fix |
|---|---|---|
| E0373: closure may outlive the current function | The closure borrows a local and `spawn` needs `'static` | Add `move` |
| E0382: borrow of moved value | The parent used a value after moving it into the closure | Clone before the closure, or restructure so only the thread uses it |
| E0382: value moved in previous iteration of loop | A loop moved the same value into several closures | Clone inside the loop, or share with `Arc` |
| E0597: borrowed value does not live long enough | A moved reference still points at a local | Move the owned data, or use `thread::scope` |
| E0277: cannot be sent between threads safely | A captured type is not `Send`, such as `Rc` | Use a thread-safe type such as `Arc` |
Why this design is worth the friction
Because spawn demands 'static and Send, the compiler can prove that a spawned thread never holds a dangling reference. Because a moved value leaves the parent unusable, two threads cannot both mutate it. Ownership transfer is the first of the compile-time rules that make data races a compile-time error in Rust. The next chapter explains Send and Sync, the traits that extend these rules to every type.
Exercise
The code below fails to compile. Name the error code, explain why it happens, and give two different fixes that keep main able to print text at the end.
let text = String::from("hi");
let h = std::thread::spawn(|| println!("{text}"));
h.join().unwrap();
println!("{text}");
Show answer
The error is E0373. The closure captures text by shared reference, so it borrows a local variable, and spawn requires the closure to be 'static because the thread may outlive main's stack frame. Fix 1: clone first and move the clone, with let t = text.clone(); spawn(move || println!("{t}")). Fix 2: wrap the string in an Arc, clone the Arc for the thread, and move that clone. Plain move alone is not a fix, because it moves text into the closure and the final println! then fails with E0382.
Exercise
A program spawns threads in a for loop, and each closure uses a Vec<u8> called buffer that was created before the loop. Compilation fails with "value moved into closure here, in previous iteration of loop". Why does this happen, and what is the simplest change that makes each thread get its own data?
Show answer
A move closure takes ownership of buffer, and the first iteration consumes it, so the second iteration has nothing left to move. The simplest change is to put let buffer = buffer.clone(); at the top of the loop body so each closure moves its own clone. If the threads only read the data and it is large, an Arc<Vec<u8>> cloned per iteration avoids copying the bytes.