Sub topic 9
Why spawned tasks must be Send and 'static
This chapter assumes you know ownership and borrowing, the Send and Sync marker traits at a basic level, Arc and Rc, and the move keyword on closures. It also assumes you can start a Tokio runtime and call tokio::spawn. By the end you should be able to read the two most common spawn compiler errors and fix them.
The signature that causes the errors
Both requirements come from the signature of tokio::spawn:
pub fn spawn<F>(future: F) -> JoinHandle<F::Output>
where
F: Future + Send + 'static,
F::Output: Send + 'static,The future must be Send and 'static. Its output must be too, because the output is handed to whichever task awaits the JoinHandle. The two bounds protect against different problems.
| Bound | Question it answers | Typical error |
|---|---|---|
| `'static` | Can the task outlive the code that spawned it? | "borrowed value does not live long enough" |
| `Send` | Can the task be moved to another thread? | "future cannot be sent between threads safely" |
'static: the task can outlive its parent
spawn returns immediately and the task runs on its own. The function that called spawn may return, and its local variables are then dropped. If the task still held a reference to one of those variables, the reference would dangle. The compiler cannot prove when the task finishes, so it requires that the task borrows nothing from the local scope.
#[tokio::main]
async fn main() {
let name = String::from("Ferris");
// Does not compile: the async block borrows `name`.
let handle = tokio::spawn(async {
println!("{name}");
});
handle.await.unwrap();
}The error says the closure or async block "may outlive the current function, but it borrows name". The fix is to move ownership into the task:
#[tokio::main]
async fn main() {
let name = String::from("Ferris");
let handle = tokio::spawn(async move {
println!("{name}");
});
handle.await.unwrap();
}If several tasks need the same data, give each task its own handle. Clone cheap values, or wrap shared ones in Arc and clone the Arc before each spawn. The Arc is owned, so it satisfies 'static.
Why join! does not have this limit
join! and select! run futures inside the current task. They are polled by the same task that created them, so they cannot outlive it, and they may borrow local variables freely. Only spawn creates an independent task, and that is what forces 'static.
Send: the task can move between threads
Tokio's default multi-threaded runtime has a pool of worker threads. A task is polled on one worker until it returns Poll::Pending at an .await. When it is woken, any idle worker may pick it up. The task therefore starts on one thread and may resume on another.
The compiler turns an async block into a state machine. Every value that is alive across an .await becomes a field of that state machine. If one of those fields is not Send, such as an Rc, the whole future is not Send.
Here is a task that holds an Rc across an await:
use std::rc::Rc;
use std::time::Duration;
use tokio::time::sleep;
#[tokio::main]
async fn main() {
// Does not compile: Rc<i32> is not Send and lives across the await.
tokio::spawn(async {
let data = Rc::new(5);
sleep(Duration::from_millis(10)).await;
println!("{data}");
})
.await
.unwrap();
}Rc uses a non-atomic reference count. If two threads cloned or dropped it at the same time, the count could be corrupted. The compiler error names the offending type and says it "is used later" after the .await. That wording points you to the exact variable.
Fix 1: end the value's scope before the await
Only values that are alive at the .await become part of the future. If the Rc is dropped first, the future is Send:
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);
println!("{data}");
}
sleep(Duration::from_millis(10)).await;
println!("done");
})
.await
.unwrap();
}The inner block matters. Calling drop(data) explicitly does not always help, because older compilers still treat the variable as live until the end of its scope.
Fix 2: use a Send type
Replace Rc with Arc, and RefCell with a Mutex. The atomic count in Arc makes it safe to share across threads.
The std MutexGuard trap
A std::sync::MutexGuard is not Send. Holding one across an .await makes the future !Send, which causes the same error:
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::time::sleep;
#[tokio::main]
async fn main() {
let counter = Arc::new(Mutex::new(0u32));
let c = Arc::clone(&counter);
tokio::spawn(async move {
{
let mut guard = c.lock().unwrap();
*guard += 1;
} // guard dropped before the await
sleep(Duration::from_millis(10)).await;
})
.await
.unwrap();
println!("{}", *counter.lock().unwrap());
}If you need to keep the lock across an .await, use tokio::sync::Mutex instead. Its guard is Send.
When a value truly cannot be Send
Some types must stay on one thread, for example a handle from a GUI library or an Rc-based structure you cannot change. Tokio offers LocalSet for this. Tasks started with spawn_local always run on the thread that drives the LocalSet, so they need 'static but not Send.
use std::rc::Rc;
use tokio::task::LocalSet;
#[tokio::main]
async fn main() {
let local = LocalSet::new();
local
.run_until(async {
let data = Rc::new(5);
let d = Rc::clone(&data);
tokio::task::spawn_local(async move {
println!("{d}");
})
.await
.unwrap();
})
.await;
}The trade-off is that all local tasks share one thread, so they get no parallelism with each other.
Quick reference
| Symptom | Likely cause | Fix |
|---|---|---|
| "may outlive the current function, but it borrows" | Async block borrows a local | Add `move`, clone, or use `Arc` |
| "future cannot be sent between threads safely" with `Rc` | Non-atomic type held across `.await` | Use `Arc`, or drop the value before the await |
| Same error naming `MutexGuard` | std lock guard held across `.await` | Narrow the scope, or use `tokio::sync::Mutex` |
| Output type error on `JoinHandle` | Task returns a non-`Send` or borrowed value | Return an owned, `Send` value |
Exercise
A task spawned with tokio::spawn(async { println!("{}", items.len()); }) fails to compile, where items is a local Vec<String> that main also needs afterwards. Which bound is violated, and how do you fix it while keeping items usable in main?
Show answer
The 'static bound is violated, because the async block borrows items and the task could outlive it. Wrap the vector in an Arc (let items = Arc::new(items);), clone it with let items2 = Arc::clone(&items);, and write async move { println!("{}", items2.len()); }. The task owns its Arc, and main keeps its own.
Exercise
Why does holding a std::sync::MutexGuard across an .await inside a spawned task fail to compile on the multi-threaded runtime? Give two ways to fix it.
Show answer
The guard is not Send, and it is stored in the future's state across the await. The task may resume on a different worker thread, so the future as a whole is not Send. Fix it by dropping the guard in an inner block before the .await, or by using tokio::sync::Mutex, whose guard is Send.