Sub topic 16
Send futures and holding values across await
This chapter assumes you know what Send and Sync guarantee, how auto traits are derived, and the basics of async/await on the Tokio runtime. It covers why a future can be !Send, how to read the error, and how to fix it.
To run the examples, add Tokio to Cargo.toml:
[dependencies]
tokio = { version = "1", features = ["full"] }Why futures have Send bounds
An async block compiles into an anonymous struct that implements Future. The struct is a state machine. Each .await is a point where the task can pause, and the struct stores every local variable that is still alive at that point.
Send is an auto trait, so the compiler derives it from the fields. The generated future is Send only if every value kept across an .await is Send. A single Rc held across an .await makes the whole future !Send.
This matters because of how Tokio's default multi-threaded runtime works. It uses work stealing. A task can pause on one worker thread and resume on another. Resuming on another thread moves the future, and with it everything it stores, to that thread. That is the same hazard thread::spawn guards against, so the signature is similar:
pub fn spawn<F>(future: F) -> JoinHandle<F::Output>
where
F: Future + Send + 'static,
F::Output: Send + 'static,'static has the same meaning as for threads. The task may outlive the function that spawned it, so it cannot borrow local data.
The rule has two parts:
- Only values alive at an
.awaitcount. A value created and dropped between two awaits is never stored in the future. - "Alive" is decided by scope, not by your intent. A variable is still alive at the end of its enclosing block unless it was moved out.
A future that is not Send
This program does not compile:
use std::rc::Rc;
use tokio::time::{sleep, Duration};
#[tokio::main]
async fn main() {
let handle = tokio::spawn(async {
let local = Rc::new(5);
println!("{}", local);
sleep(Duration::from_millis(10)).await;
});
handle.await.unwrap();
}The Rc is last used before the .await, but its scope extends to the end of the block. The compiler therefore treats it as stored in the future.
Reading the error
The message has three parts. Read them in this order:
- The headline says the future cannot be sent between threads safely. It points at the argument to
tokio::spawn. - The
Sendis not implemented line names the offending type, hereRc<i32>. - A note says the future "is not
Sendas this value is used across an await". It points at both the variable and the.await.
The note shows which variable to fix and which .await makes it a problem.
Fix 1: end the value's scope before the await
Put the short-lived value in its own block:
use std::rc::Rc;
use tokio::time::{sleep, Duration};
#[tokio::main]
async fn main() {
let handle = tokio::spawn(async {
{
let local = Rc::new(5);
println!("{}", local);
}
sleep(Duration::from_millis(10)).await;
println!("done");
});
handle.await.unwrap();
}The Rc is dropped at the closing brace, before the .await, so it is not stored. This program prints 5 and then done.
Calling drop(local) is not a reliable substitute. The compiler's analysis has historically been scope-based, and an explicit drop may not be enough. A block always works.
The std MutexGuard trap
The most common real-world case is a std::sync::MutexGuard. A guard is !Send, because some platforms require a lock to be released on the thread that took it. Holding one across an .await makes the future !Send:
use std::sync::{Arc, Mutex};
use tokio::time::{sleep, Duration};
async fn bump(counter: Arc<Mutex<i32>>) {
let mut guard = counter.lock().unwrap();
*guard += 1;
sleep(Duration::from_millis(10)).await; // guard is still alive here
}Passing bump(counter) to tokio::spawn fails with a note pointing at guard. Scope the guard so it is released before the await:
use std::sync::{Arc, Mutex};
use tokio::time::{sleep, Duration};
async fn bump(counter: Arc<Mutex<i32>>) {
{
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(0));
let mut handles = Vec::new();
for _ in 0..4 {
handles.push(tokio::spawn(bump(Arc::clone(&counter))));
}
for handle in handles {
handle.await.unwrap();
}
println!("{}", *counter.lock().unwrap());
}This prints 4. Besides satisfying Send, it keeps the lock held for as short a time as possible.
Hidden temporaries
Not every guard has a name. A temporary lives until the end of its enclosing statement. In match m.lock().unwrap().len() { n => other(n).await }, the guard is a temporary in the match scrutinee and lives for the whole match, including the arms. The fix is to bind the result first:
- Write
let n = m.lock().unwrap().len();. The guard is dropped at the semicolon. - Use
nafter that, including across awaits.
Fix 2: use a type that is Send
Sometimes the value really must live across an .await. Replace it with a Send equivalent:
| Held across await | Problem | Replacement |
|---|---|---|
| `Rc<T>` | Non-atomic count, not `Send` | `Arc<T>` |
| `RefCell<T>` | Not `Sync`, so `&RefCell` is not `Send` | `Mutex<T>` or `RwLock<T>` |
| `std::sync::MutexGuard` | Not `Send` | `tokio::sync::MutexGuard` |
| `Box<dyn Error>` | Trait object does not promise `Send` | `Box<dyn Error + Send + Sync>` |
| Raw pointers | Opted out by default | Wrap in a type with a justified `unsafe impl Send` |
tokio::sync::Mutex is designed to be held across .await. Its lock() is itself async, and a waiting task yields instead of blocking a worker thread. The trade-off is that it is slower than the std mutex. Tokio's guidance is to use std::sync::Mutex when the critical section is short and never awaits, and the Tokio mutex only when you must hold the lock over an .await.
The trait object row catches many people. A function returning Result<(), Box<dyn Error>> can make its future !Send whenever such an error value is alive at an .await. This usually happens through ?, which stores the error value.
Fix 3: do not require Send
Send is only required because the runtime may move the task. If the task stays on one thread, Rc is fine. Tokio offers spawn_local on a LocalSet, which accepts !Send futures:
use std::rc::Rc;
use tokio::task::LocalSet;
use tokio::time::{sleep, Duration};
#[tokio::main(flavor = "current_thread")]
async fn main() {
let local = LocalSet::new();
local
.run_until(async {
let shared = Rc::new(5);
let for_task = Rc::clone(&shared);
let handle = tokio::task::spawn_local(async move {
sleep(Duration::from_millis(10)).await;
println!("task sees {}", for_task);
});
handle.await.unwrap();
println!("main sees {}", shared);
})
.await;
}This prints task sees 5 and then main sees 5. Every task in a LocalSet runs on the thread that drives the set, so no value ever crosses threads. You give up spreading tasks across cores.
Choosing a fix
Edge cases
- Generic code. A generic async function is
Sendonly if its type parameters are. You may needT: Sendon the function. The compiler reports the missing bound at the spawn site, not at the function definition. - Borrows. Holding
&Tacross an.awaitrequiresT: Sync, because&TisSendexactly whenTisSync. This is the relation you learned earlier, now applied to a future's stored fields. 'static.Senderrors and'staticerrors are separate. A future can beSendand still fail because it borrows a local. Useasync moveand owned orArcdata.- Auto trait leakage. A function returning
impl Futureexposes whether the future isSend. A later change inside the body, such as adding anRc, can break callers who spawn it.
Exercise
A task spawned with tokio::spawn locks a std::sync::Mutex, increments the value through the guard, then calls .await on a network read while the guard variable is still in scope. The compiler rejects the spawn. Why, and what are two ways to fix it?
Show answer
The guard is alive at the .await, so it is stored in the generated future. std::sync::MutexGuard is not Send, so the future is not Send, and tokio::spawn requires Send because the task may resume on another worker thread. Fix 1: put the lock and the increment in an inner block (or copy the result into a local) so the guard is dropped before the .await. Fix 2: use tokio::sync::Mutex, whose guard is Send and may be held across an .await, at the cost of a slower lock.
Exercise
Why does let n = m.lock().unwrap().len(); other(n).await; compile in a spawned task, while match m.lock().unwrap().len() { n => other(n).await } can fail?
Show answer
In the first form the guard is a temporary dropped at the end of the let statement, so nothing non-Send is alive at the .await. In the match, the temporary in the scrutinee lives until the end of the whole match, including the arms. The guard is therefore still alive at the .await and makes the future !Send.