Sub topic 11
Why thread::spawn requires Send and 'static
This chapter assumes you know ownership, borrowing and lifetimes, trait bounds, closures with move, and the basics of thread::spawn and JoinHandle. It also assumes you know what Send and Sync promise. Here you will see how those traits and the 'static lifetime bound combine in the signature of thread::spawn, and how to read the errors they produce.
The signature
This is the standard library definition, simplified slightly:
pub fn spawn<F, T>(f: F) -> JoinHandle<T>
where
F: FnOnce() -> T + Send + 'static,
T: Send + 'static,There are three separate requirements:
F: Send. The closure moves to another thread, so everything it captures must be safe to move there.F: 'static. The closure must not hold any borrow that could expire before the thread finishes.T: Send + 'static. The return value travels back throughJoinHandle::join, so it crosses threads too. It also must not borrow from the spawning thread's stack.
FnOnce fits because the new thread runs the closure exactly once.
What 'static means here
A 'static bound does not mean "lives for the whole program". It means the type contains no references with a lifetime shorter than 'static. An owned String satisfies String: 'static, because it holds no borrows at all. The value can still be dropped early, for example when the thread finishes.
Why 'static is needed: the thread can outlive its parent
The compiler cannot know when a spawned thread ends. The caller may return first, which destroys its stack frame. A borrow into that frame would then dangle. Consider:
use std::thread;
fn main() {
let v = vec![1, 2, 3];
let handle = thread::spawn(|| {
println!("{:?}", v);
});
handle.join().unwrap();
}This does not compile. The error is E0373: the closure may outlive the current function, but it borrows v. You may object that join waits for the thread, so the borrow is safe. That is true here, but the signature of spawn does not encode it. Nothing forces you to call join, and you can drop the JoinHandle to detach the thread.
The usual fix is move, which transfers ownership into the closure:
use std::thread;
fn main() {
let v = vec![1, 2, 3];
let handle = thread::spawn(move || {
println!("{:?}", v);
});
handle.join().unwrap();
}This prints [1, 2, 3]. The closure now owns v, so it contains no borrows and is 'static. Vec<i32> is Send, so the Send bound passes as well.
Why Send is needed: the closure's captures change threads
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 hidden struct. Capturing an Rc breaks it:
use std::rc::Rc;
use std::thread;
fn main() {
let data = Rc::new(5);
let handle = thread::spawn(move || {
println!("{}", data);
});
handle.join().unwrap();
}This fails with E0277: Rc<i32> cannot be sent between threads safely, and the compiler notes that the trait Send is not implemented for Rc<i32>. The note also says the requirement comes from the Send bound on spawn. The reason is that Rc updates its reference count without atomic operations. If two threads clone or drop their handles at the same time, the count can be corrupted.
Captured references add a second rule. A closure that captures &T is Send only if &T is Send, and &T is Send exactly when T: Sync. So Send on the closure can require Sync on the data it borrows.
Combining both bounds: sharing static data by reference
References can satisfy 'static too, if they point at data that lives for the whole program. Box::leak produces such a reference by deliberately never freeing the allocation:
use std::thread;
fn main() {
let data: &'static Vec<i32> = Box::leak(Box::new(vec![1, 2, 3]));
let a = thread::spawn(move || data.len());
let b = thread::spawn(move || data.iter().sum::<i32>());
println!("len = {}, sum = {}", a.join().unwrap(), b.join().unwrap());
}This prints len = 3, sum = 6. The shared reference is Copy, so each thread gets its own copy of the reference. Both checks pass. The reference is 'static, and &Vec<i32> is Send because Vec<i32> is Sync. The cost is a leaked allocation, which is acceptable for program-wide configuration and wasteful anywhere else.
The return value is checked too
The result of the closure is stored in a slot shared with the JoinHandle, and join hands it to the parent thread. Because the value is created on one thread and consumed on another, T: Send is required. The 'static requirement prevents the closure from returning a borrow of something that the thread's own stack or the parent's stack still owns.
use std::thread;
fn main() {
let handle = thread::spawn(|| {
let words = vec![String::from("alpha"), String::from("beta")];
words.join("-")
});
println!("{}", handle.join().unwrap());
}This prints alpha-beta. Returning an Rc from the closure would fail the T: Send check in the same way as capturing one.
Your own generic functions need the same bounds
If you wrap spawn in a generic function, the compiler requires you to state the bounds yourself. It cannot assume a type parameter T satisfies them:
use std::fmt::Debug;
use std::thread;
fn print_on_thread<T>(value: T) -> thread::JoinHandle<()>
where
T: Debug + Send + 'static,
{
thread::spawn(move || println!("{:?}", value))
}
fn main() {
print_on_thread(vec![1, 2, 3]).join().unwrap();
print_on_thread("hi").join().unwrap();
}The output is [1, 2, 3] and then "hi". If you leave out Send, you get E0277 on the closure. If you leave out 'static, you get an error such as "the parameter type T may not live long enough". In both cases, add the missing bound to your function.
Choosing a way to satisfy the bounds
| Situation | Tool | Why it works |
|---|---|---|
| One thread needs the data and nobody else does | `move` closure | The closure owns the value |
| Several threads share mutable state | `Arc<Mutex<T>>` or `Arc<RwLock<T>>` | `Arc` is `'static` and `Send` when its contents are `Send + Sync` |
| Several threads read local data and all finish before the function returns | `thread::scope` | The scope guarantees the threads end first, so borrows are safe |
| Read-only data for the whole program | `static`, or `Box::leak` | The reference is `'static` |
| Passing results between threads | `mpsc::channel` | Each message is moved, so it needs `Send` and ownership |
Common mistakes
- Reaching for
movewhen the error is aboutSend.movefixes lifetime errors (E0373) but does nothing forRcor other non-Sendcaptures. - Cloning an
Arcinside the closure instead of before it. The clone must happen on the spawning thread, then move into the closure. - Assuming
joinremoves the'staticrequirement. It does not. Usethread::scopewhen you want borrowing. - Holding a
MutexGuardin a value you move into a spawned closure. The guard is notSendon common platforms, so the error appears at thespawncall, not at the lock.
Exercise
A function creates let name = String::from("log"); and then calls thread::spawn(|| println!("{}", name));. Which bound causes the error, what is the error code, and what are two ways to fix it?
Show answer
The 'static bound fails, because the closure borrows name from the function's stack frame. The error is E0373 ("closure may outlive the current function"). Fix 1: add move so the closure owns the String. Fix 2: use thread::scope and spawn through the scope, which lets the thread borrow name because the scope waits for it to finish.
Exercise
A closure passed to thread::spawn captures Arc<RefCell<i32>>. The Arc is 'static, so why does the call still fail, and which bound reports it?
Show answer
Arc<T> is Send only when T is both Send and Sync. RefCell<i32> is Send but not Sync, so Arc<RefCell<i32>> is not Send. The closure therefore fails the F: Send bound with E0277. Replacing RefCell with Mutex fixes it.