Sub topic 7
Why spawned tasks must be Send and 'static
This chapter assumes you know Rust ownership, borrowing and lifetimes, and that you are comfortable with traits, generics and closures. You should also have used tokio::spawn as shown in the previous chapter. It explains two compiler errors that most Tokio beginners hit, and why they exist.
The signature behind the errors
Here is tokio::spawn, slightly simplified:
pub fn spawn<F>(future: F) -> JoinHandle<F::Output>
where
F: Future + Send + 'static,
F::Output: Send + 'static,Three requirements follow from it:
- The future must be
'static. It may not hold borrows of local variables. - The future must be
Send. Every value that lives across an.awaitmust be safe to move to another thread. - The output must be
Send + 'static, because theJoinHandlecan be awaited from a different task on a different thread.
Each requirement comes from how the runtime works. spawn hands your future to the scheduler and returns immediately. After that, the scheduler decides when and where to poll it.
Why 'static: the task outlives its caller
When spawn returns, the calling function can keep running or finish. The spawned task keeps running regardless, and it is not tied to the caller's stack frame. If the task borrowed a local variable, it could read that variable after the function had returned. Rust forbids this, so the task may not borrow anything that is not 'static.
#[tokio::main]
async fn main() {
let name = String::from("tokio");
let handle = tokio::spawn(async {
println!("hello {name}");
});
handle.await.unwrap();
}This does not compile. The error looks like this:
error[E0373]: async block may outlive the current function, but it borrows `name`, which is owned by the current function'static here is a bound on the type, not a claim that the value lives forever. A bound T: 'static means "T contains no borrows shorter than the whole program". An owned String satisfies it. A &String pointing at a local does not.
The fix is to move ownership into the task with async move:
#[tokio::main]
async fn main() {
let name = String::from("tokio");
let handle = tokio::spawn(async move {
println!("hello {name}");
});
handle.await.unwrap();
}Sharing one value between several tasks
After a move, the original owner can no longer use the value. When several tasks need the same data, wrap it in an Arc and give each task its own clone:
use std::sync::Arc;
#[tokio::main]
async fn main() {
let config = Arc::new(String::from("shared config"));
let mut handles = Vec::new();
for i in 0..3 {
let config = Arc::clone(&config);
handles.push(tokio::spawn(async move {
println!("task {i} sees {config}");
}));
}
for h in handles {
h.await.unwrap();
}
}Cloning an Arc copies a pointer and bumps a reference count. It does not copy the data. The shadowed name config inside the loop is a common idiom. The clone is made before spawn, so the task owns it.
Borrowing is still possible without spawn
Tokio has no "scoped" spawn that allows borrows. If you only need concurrency and not independent lifetimes, use join!. Its futures run inside the current task, so they can borrow from it.
use std::time::Duration;
use tokio::time::sleep;
async fn length_after_delay(text: &str) -> usize {
sleep(Duration::from_millis(50)).await;
text.len()
}
#[tokio::main]
async fn main() {
let name = String::from("tokio");
let (a, b) = tokio::join!(length_after_delay(&name), length_after_delay(&name));
println!("{a} {b}");
}Why Send: tasks move between threads
On the default multi-thread runtime, a task can be polled by one worker thread, suspend at an .await, and resume on a different worker thread. The future is a state machine, and everything it keeps alive across an .await is stored inside it. When the future moves threads, all of that stored data moves too. So the future is Send only if every value held across an .await is Send.
The Rc example
Rc uses a non-atomic reference count, so it is not Send. Holding one across an .await makes the whole future non-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);
sleep(Duration::from_millis(10)).await;
println!("{data}");
});
handle.await.unwrap();
}The compiler rejects this with a message like future cannot be sent between threads safely. It also adds a note saying the future "is not Send as this value is used across an await". That note points at the exact variable.
The rule applies only to values that are alive across an .await. If the non-Send value is dropped before the next .await, it is never stored in the future. A block scope does this:
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;
println!("done");
});
handle.await.unwrap();
}The MutexGuard trap
The most common real-world case is a std::sync::MutexGuard. It is not Send, so holding it across an .await fails to compile in a spawned task.
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::time::sleep;
async fn increment(counter: Arc<Mutex<u32>>) {
{
let mut guard = counter.lock().unwrap();
*guard += 1;
}
sleep(Duration::from_millis(10)).await;
}
#[tokio::main]
async fn main() {
let counter = Arc::new(Mutex::new(0u32));
tokio::spawn(increment(Arc::clone(&counter))).await.unwrap();
println!("{}", *counter.lock().unwrap());
}The guard lives inside its own block, so it is dropped before the .await. If you need to hold a lock across an .await, use tokio::sync::Mutex, which is covered in the shared-state chapter.
Bounds in generic code
A helper that wraps tokio::spawn must repeat the bounds, or the compiler reports that they are missing:
use std::future::Future;
use tokio::task::JoinHandle;
fn run<F>(future: F) -> JoinHandle<F::Output>
where
F: Future + Send + 'static,
F::Output: Send + 'static,
{
tokio::spawn(future)
}
#[tokio::main]
async fn main() {
let value = run(async { 21 * 2 }).await.unwrap();
println!("{value}");
}Leaving out F::Output: Send + 'static is a frequent mistake. The error then names the output type, not the future.
When you really need non-Send data
Some data is inherently single-threaded, such as Rc, RefCell-based state and some FFI handles. Tokio offers spawn_local for this. It runs tasks on the current thread only, so they need not be Send. It must run inside a LocalSet:
use std::rc::Rc;
use tokio::task::LocalSet;
#[tokio::main(flavor = "current_thread")]
async fn main() {
let local = LocalSet::new();
local
.run_until(async {
let data = Rc::new(5);
let copy = Rc::clone(&data);
let handle = tokio::task::spawn_local(async move {
println!("local task sees {copy}");
});
handle.await.unwrap();
})
.await;
}spawn_local removes only the Send requirement. The future must still be 'static.
Quick reference
| Compiler message | Cause | Usual fix |
|---|---|---|
| `may outlive the current function, but it borrows` | The task borrows a local | Use `async move` and give the task owned data |
| `cannot be moved after being moved` style errors in a loop | One value moved into many tasks | Clone an `Arc` or the value per iteration |
| `future cannot be sent between threads safely` | A non-`Send` value is alive across an `.await` | Drop it before the `.await`, or use a `Send` type |
| `MutexGuard` is not `Send` | A std lock guard is held across an `.await` | Shorten the guard's scope, or use `tokio::sync::Mutex` |
| Missing `Send` or `'static` in a generic helper | The where-clause lacks the bounds | Copy the bounds from `spawn` |
Exercise
A task spawned with tokio::spawn uses a Vec<String> called items that is owned by main. You want three tasks to read it, and main also wants to read it afterwards. Why does async { println!("{}", items.len()) } fail, and how do you fix it?
Show answer
The async block borrows items, and a spawned task must be 'static, because it can outlive the function that created it. Wrap the vector in an Arc (let items = Arc::new(items);). In each loop iteration make let items = Arc::clone(&items);, then spawn with async move { ... }. Each task owns its own Arc, which satisfies 'static, and main keeps its handle to the same data.
Exercise
A spawned task creates an Rc<u32>, awaits a timer, then prints the Rc. The compiler says the future is not Send. Name two different ways to fix it.
Show answer
Either limit the Rc to a block that ends before the .await, so it is never stored in the future, or replace Rc with Arc, which is Send. A third option is to run the task with spawn_local inside a LocalSet, which does not require Send.