Sub topic 16
Why some futures are not Send
This chapter assumes you know the Send and Sync marker traits, Arc, and how an async fn becomes a state machine. Earlier chapters covered that last point. Here you will learn which values make a future !Send, how to read the compiler's complaint, and how to fix it.
Send applies to the whole state machine
Send is an auto trait. A type is Send if all of its fields are Send. An async fn compiles to an anonymous struct or enum. Its fields are the values that must survive a suspension: the arguments, plus every local variable still alive at an .await. So a future is Send only if every one of those saved values is Send.
A local that is created and dropped between two .await points is never stored in the state machine. It lives on the thread's stack for one poll call. It does not affect Send.
Why it matters: tasks can change threads
A multi-threaded runtime keeps tasks in a shared queue. When a waker fires, any worker thread may pick the task up and call poll. A task can start on thread A, suspend, and resume on thread B. Every value in its state machine is then moved across threads, and that is exactly what Send guards.
This is why spawn functions on multi-threaded runtimes, such as tokio::spawn, require Future + Send + 'static. A simple block_on like the one you built earlier polls on one thread only, so it needs no Send bound.
Common types that are not Send
| Type | Send | Effect when held across `.await` |
|---|---|---|
| `Rc<T>` | No | Future is `!Send`. Its reference count is not atomic. |
| `std::sync::MutexGuard<T>` | No | Future is `!Send`. A lock must be released on the thread that took it on some platforms. |
| `RefCell<T>` by reference | `&RefCell<T>` is not `Send` because `RefCell` is not `Sync` | Future is `!Send`. |
| Raw pointers `*const T`, `*mut T` | No | Future is `!Send` unless you wrap them and implement `Send` yourself. |
| `Arc<Mutex<T>>` | Yes, if `T: Send` | Fine. |
The reference rule is worth memorizing: &T is Send exactly when T is Sync. Holding a &Cell<u32> across an .await makes the future !Send even though Cell<u32> is itself Send.
Reproducing the error
This future holds an Rc across an .await, so it is not Send:
use std::rc::Rc;
async fn tick() {}
async fn uses_rc() {
let data = Rc::new(5);
tick().await;
println!("{data}");
}The code above compiles on its own. The error appears when something demands Send, such as tokio::spawn(uses_rc()) or a function like assert_send(&uses_rc()). The message reads roughly "future cannot be sent between threads safely", followed by a note "within impl Future, the trait Send is not implemented for Rc<i32>". It also says "data is used here across an await" and points at the .await.
The error is reported at the use site, not at the async fn. That is because an async fn returns impl Future, and auto traits leak through impl Trait. The compiler checks Send only where you ask for it.
Fixing it by ending the value's scope
The usual fix is to make sure the non-Send value is dead before the .await. A block gives it a short scope:
use std::rc::Rc;
use std::sync::Mutex;
async fn tick() {}
fn assert_send<T: Send>(_: &T) {}
async fn scoped_rc() {
{
let data = Rc::new(5);
println!("{data}");
}
tick().await;
}
async fn scoped_guard(m: &Mutex<u32>) {
{
let mut guard = m.lock().unwrap();
*guard += 1;
}
tick().await;
}
fn main() {
let f = scoped_rc();
assert_send(&f);
let m = Mutex::new(0);
let g = scoped_guard(&m);
assert_send(&g);
println!("both futures are Send");
}scoped_guard holds a &Mutex<u32> for its whole life. That is fine because Mutex<u32> is Sync, so the reference is Send. The guard itself is gone before the .await.
Other ways to fix it
Pick the option that fits the situation:
- Shorten the scope. Compute what you need from the guard or
Rc, end the block, then await. This is the cheapest fix. - Use a thread-safe type. Replace
RcwithArcandRefCellwithMutex. This costs atomic operations, but the code stays simple. - Use an async-aware lock. Tokio's
tokio::sync::Mutexhas a guard that isSend, and it is the right choice when you must hold a lock across an.await. Holding it across suspension still blocks other tasks that want the lock, so keep those sections short. - Stay on one thread.
tokio::task::spawn_localinside aLocalSet, or a current-thread runtime, never moves a task between threads, so it needs noSendbound.
Trait objects drop the guarantee
Auto traits leak through impl Future but not through dyn Future. The boxed future from the pinning chapter erases the concrete type, so it also erases Send. You must write the bound yourself:
use std::future::Future;
use std::pin::Pin;
fn boxed_send(n: u32) -> Pin<Box<dyn Future<Output = u32> + Send>> {
Box::pin(async move { n + 1 })
}
fn main() {
let _fut = boxed_send(1);
}Without + Send, the return type would compile but would be rejected by any multi-threaded spawn. If the async block inside held an Rc across an .await, adding + Send would turn that into a compile error at the Box::pin call.
Guarding against regressions
Because Send leaks through impl Future, a harmless change can silently make a public future !Send. For example, adding an Rc inside a helper breaks every caller that spawns it. Library authors often add a compile-time check, like the assert_send function above, to a test or an unused function. It fails the build the moment a future stops being Send.
Reading the diagnostic
When the compiler rejects a spawn, look for these parts of the message:
- The name of the type that is not
Send, such asRc<i32>orMutexGuard<'_, u32>. - The
.awaitthe value lives across, which the note marks as "await occurs here". - The line where the value was created. Move the
.awaitor end the scope before it.
If the type is hidden inside a library call, bisect. Comment out half of the function body and see whether the error disappears.
Exercise
A task holds let n = std::cell::Cell::new(0u32); let r = &n; and then runs tick().await while still using r afterwards. Is the future Send? Explain, and give one fix.
Show answer
No. r is a &Cell<u32>, and &T is Send only if T: Sync. Cell<u32> is not Sync, so the saved reference makes the future !Send. Fixes: finish using n in an inner block before the .await, or replace Cell<u32> with AtomicU32, which is Sync.
Exercise
You write fn make() -> Pin<Box<dyn Future<Output = ()>>> returning Box::pin(async { tick().await }) and later tokio::spawn(make()) fails to compile even though the async block holds no Rc. Why, and how do you fix the signature?
Show answer
A dyn Future type does not carry auto traits unless you name them. Without + Send, the compiler cannot assume the boxed future is Send. Change the return type to Pin<Box<dyn Future<Output = ()> + Send>>.