Sub topic 16
Send futures and holding values across await
This chapter assumes you know async fn, .await, and the Send bound on thread::spawn. You don't need a specific runtime. The examples only check trait bounds, so they need no external crates.
Why futures have to be Send
An async fn returns a future. The compiler turns the function body into a state machine, which is a struct that stores every local variable still needed after an .await. A multi-threaded runtime such as Tokio can resume a task on a different thread than the one that paused it. So tokio::spawn requires the future to be Send, just as thread::spawn requires its closure to be Send.
Futures are auto-trait types, like structs. A future is Send only if every value stored in its state machine is Send. A value that never lives across an .await is not stored there, so it doesn't count.
A future that is not Send
Rc is not Send. The next program holds an Rc across an .await. It does not compile, which is the point of the example.
use std::rc::Rc;
async fn yield_now() {}
async fn bad() {
let data = Rc::new(5);
yield_now().await;
println!("{}", data);
}
fn assert_send<T: Send>(_: T) {}
fn main() {
assert_send(bad());
}The error says the future returned by bad "cannot be sent between threads safely". It then points at the .await and notes that Rc<i32> is "used later" and "is not Send". Read the note after the first line. It names the value and the await point that cause the problem.
Fixing it by shortening the lifetime
The usual fix is to end the value's scope before the .await. If nothing is alive at the await point, nothing is stored.
use std::rc::Rc;
async fn yield_now() {}
async fn good() {
{
let data = Rc::new(5);
println!("{}", data);
}
yield_now().await;
}
fn assert_send<T: Send>(_: T) {}
fn main() {
assert_send(good());
println!("ok");
}This prints ok. The compiler's analysis follows scopes, so calling drop(data) before the .await can still produce the error. Use a block, as above.
Other fixes:
- Swap the type for a
Sendone, for exampleArcinstead ofRc. - Clone or copy the data you need out of the non-
Sendvalue, then let the original go out of scope. - Run the future on a single-threaded executor or a local task set. These accept non-
Sendfutures.
Guards held across await
The most common real case is std::sync::MutexGuard. It is not Send, because some platforms require a lock to be released on the thread that took it. Locking, then awaiting, then using the guard makes the future non-Send.
Checking early
Write assert_send(my_future()) in a test or helper, as above. The error then appears next to the function that caused it, instead of at a distant spawn call.
Exercise
An async function locks a std::sync::Mutex, awaits a network call, then reads the guard. tokio::spawn rejects it. Why, and what is one fix?
Show answer
MutexGuard is not Send and is alive at the .await, so it is stored in the future and makes the whole future non-Send. One fix is to read the needed value into a local and let the guard go out of scope in a block before the .await. Another is to use an async-aware mutex.