Sub topic 11
Why thread::spawn requires Send and 'static
This chapter assumes you know closures and move, basic use of thread::spawn and JoinHandle, and trait bounds. It also assumes you have met Send and Sync as marker traits.
The signature
Here is the signature of thread::spawn, simplified:
pub fn spawn<F, T>(f: F) -> JoinHandle<T>
where
F: FnOnce() -> T + Send + 'static,
T: Send + 'static,It has two separate requirements. Send is about which thread may own a value. 'static is about how long the value may live. Each one rules out a different bug.
Why the closure must be Send
A spawned closure is built on one thread and runs on another. Everything it captures moves to the new thread. If a captured value is not Send, that move is unsafe. Rc<T> is the classic case. Its reference count is not atomic, so two threads touching clones of one Rc could corrupt the count.
The compiler checks F: Send. A closure is Send only if every captured value is Send. This is the auto-trait rule from earlier chapters, applied to the closure's captured fields.
Why the closure must be 'static
The parent thread can return before the child finishes. If the child held a reference to a local variable, that reference would dangle once the parent's stack frame was gone. The compiler cannot know how long a spawned thread will run, so it demands 'static. The closure may not borrow anything that could end sooner than the whole program.
use std::thread;
fn main() {
let v = vec![1, 2, 3];
let handle = thread::spawn(|| {
println!("{:?}", v);
});
handle.join().unwrap();
}This fails with error E0373: the closure "may outlive the current function, but it borrows v". The closure captured v by reference, so it is not 'static.
The usual fix is move, which transfers ownership into the closure:
use std::thread;
fn main() {
let names = vec![String::from("a"), String::from("b")];
let handle = thread::spawn(move || {
println!("{:?}", names);
names.len()
});
println!("{}", handle.join().unwrap());
}This prints ["a", "b"] and then 2. The closure owns names, so it has no borrowed lifetime. Vec<String> is Send, so the move is allowed.
Why the return type is bounded too
T: Send is needed because join hands the result to the parent thread, so the value crosses threads a second time. T: 'static is needed because the result may be stored in the JoinHandle long after the child's stack is gone.
Which fix to choose
| Error | Cause | Typical fix |
|---|---|---|
| `cannot be sent between threads safely` | A captured type is not `Send` | Replace `Rc` with `Arc`, or `RefCell` with `Mutex` |
| `closure may outlive the current function` | The closure borrows a local | Add `move`, clone the data, or use `thread::scope` |
| `borrowed value does not live long enough` | A reference of limited lifetime is captured | Own the data, or use scoped threads |
If you only need to borrow local data and wait for the threads to finish, thread::scope removes the 'static requirement. The next chapter covers it.
Exercise
A closure captures r, a &String pointing to a local variable, and is passed to thread::spawn with move. Is the Send bound or the 'static bound violated?
Show answer
The 'static bound. &String is Send because String is Sync, so the move to another thread is fine. But move only copies the reference into the closure. The reference still points to a local and has a limited lifetime, so the closure is not 'static.