Sub topic 8
Why spawned tasks must be Send and 'static
This chapter assumes you know ownership, closures with move, Arc, and the basics of tokio::spawn. It explains the two bounds on tokio::spawn and how to fix the compiler errors they cause.
The signature behind the errors
pub fn spawn<F>(future: F) -> JoinHandle<F::Output>
where
F: Future + Send + 'static,
F::Output: Send + 'static,Both the future and its output must be Send and 'static. Each bound exists for a different reason.
Why 'static
A spawned task is independent. It can outlive the function that created it, so it cannot borrow from that function's stack. 'static means the future holds no non-static references. Owned data satisfies it, and so do references to data that lives for the whole program.
#[tokio::main]
async fn main() {
let name = String::from("Ferris");
let handle = tokio::spawn(async {
println!("{name}");
});
handle.await.unwrap();
}This fails with an error saying the async block "may outlive the borrowed value name". Add move so the block takes ownership:
#[tokio::main]
async fn main() {
let name = String::from("Ferris");
let handle = tokio::spawn(async move {
println!("{name}");
});
handle.await.unwrap();
}To use the same value in several tasks, clone it or wrap it in Arc and move one handle into each task.
Why Send
On Tokio's multi-threaded runtime, a task can be paused at an .await and resumed on a different worker thread. Everything the future holds across an .await moves with it. A type that is not Send, such as Rc, must not change threads, so the compiler rejects it.
use std::rc::Rc;
use std::time::Duration;
use tokio::time::sleep;
#[tokio::main]
async fn main() {
tokio::spawn(async {
let data = Rc::new(5);
sleep(Duration::from_millis(10)).await;
println!("{data}");
});
}The error says the future "cannot be sent between threads safely" because Rc<i32> is held across an await point.
Only values alive across an .await matter. If the non-Send value is dropped before the await, the future is Send:
use std::rc::Rc;
use std::time::Duration;
use tokio::time::sleep;
#[tokio::main]
async fn main() {
let handle = tokio::spawn(async {
{
let data = Rc::new(5);
println!("{data}");
}
sleep(Duration::from_millis(10)).await;
});
handle.await.unwrap();
}Fixing the errors
| Error | Cause | Fix |
|---|---|---|
| borrowed value does not live long enough | Task borrows a local | Add `move`, clone, or use `Arc` |
| future cannot be sent between threads | Non-`Send` value held across `.await` | Narrow its scope, or swap `Rc` for `Arc` |
| `Send` needed for the output | Task returns a non-`Send` type | Return an owned `Send` type |
If you need a non-Send future, tokio::task::spawn_local inside a LocalSet runs it on a single thread without the Send bound. It still needs 'static.
Exercise
Why does tokio::spawn(async { println!("{v}") }) fail when v is a local Vec<i32>, and what is the smallest fix?
Show answer
The task may outlive the function, so it cannot borrow v, and the future is not 'static. Add move (async move { ... }) so the task owns v. If v is needed elsewhere, clone it or share it through Arc.