Sub topic 7
Why spawned tasks must be Send and 'static
This chapter assumes you know ownership, borrowing and lifetimes, closures, and Arc and Mutex from std. It also assumes you can already spawn a task with tokio::spawn.
The two bounds
The signature of tokio::spawn is roughly this:
pub fn spawn<F>(future: F) -> JoinHandle<F::Output>
where
F: Future + Send + 'static,
F::Output: Send + 'static,The future and its output must both satisfy two bounds:
'staticmeans the future holds no borrows of local data that could end before the task does.Sendmeans the future can be moved to another thread.
Why 'static
A spawned task is detached. It can keep running after the function that spawned it returns, so the compiler cannot prove any local variable outlives it. 'static does not mean "lives forever". It means the value contains no non-static references. Owned values such as String and Arc<T> satisfy it.
#[tokio::main]
async fn main() {
let name = String::from("tokio");
// Error: the closure may outlive `name`, which it only borrows.
// tokio::spawn(async { println!("{name}"); });
// Fix: move ownership into the task.
let handle = tokio::spawn(async move {
println!("{name}");
});
handle.await.unwrap();
}If several tasks need the same data, clone it or wrap it in an Arc before each move.
Why Send
On the multi-thread runtime, a task can pause at an .await and resume on a different worker thread. Everything the future stores across that .await moves with it, so all of it must be Send.
Types such as Rc and std::sync::MutexGuard are not Send. The compiler error shows up when you hold one across an .await.
use std::rc::Rc;
use std::time::Duration;
use tokio::time::sleep;
#[tokio::main]
async fn main() {
let handle = tokio::spawn(async {
{
let local = Rc::new(5);
println!("{local}");
} // `local` is dropped before the await, so the future stays Send.
sleep(Duration::from_millis(10)).await;
});
handle.await.unwrap();
}If you keep local alive past the sleep(...).await, the future is no longer Send and the program fails to compile. The error says the future "cannot be sent between threads safely" and points at the value held across the .await.
Fixing common errors
| Error cause | Fix |
|---|---|
| Borrowing a local variable | Use `async move` and pass owned data |
| Sharing data between tasks | Use `Arc`, cloned once per task |
| `Rc` or `RefCell` in the task | Use `Arc` or `Mutex` |
| `std` `MutexGuard` held across `.await` | Drop it in an inner block before awaiting |
Other runtimes
tokio::task::spawn_local accepts non-Send futures, but it needs a LocalSet and runs the task on one thread only. The 'static bound still applies.
Exercise
Why does tokio::spawn(async { println!("{name}"); }) fail to compile when name is a local String, and what is the smallest fix?
Show answer
The async block borrows name, but a spawned task must be 'static because it can outlive the function that owns name. Add move (async move { ... }) so the task takes ownership of name.
Exercise
A task creates an Rc<i32>, then calls sleep(...).await, then uses the Rc again. Why is the task rejected by tokio::spawn?
Show answer
The Rc is alive across the .await, so it is stored in the future. Rc is not Send, so the future is not Send, and the task could not safely move between worker threads.