skip to content

Send Futures and Spawning

A future is Send only if everything it holds across an .await is Send, which multi-threaded spawning requires. Interviewers ask why holding a MutexGuard across .await breaks the build.

on this pageshow

questions

5

In Rust, why does a multi-threaded executor's spawn function demand a future that is both `Send` and `'static`, and how does `async move` help?

level: juniorimportance: must knowfreq 70%

answer

  1. the task outlives the caller
  2. any worker may resume it
  3. borrowed locals break 'static
  4. async move takes ownership
  5. share through an Arc clone

basics

~20 s

A spawned future may be resumed on any worker thread and may outlive the function that spawned it, so the spawn function requires Send and 'static. An async move block owns the variables it captures instead of borrowing them.

solid answer

~40 s

Multi-threaded spawn functions declare the bound in their signature: `futures::executor::ThreadPool::spawn_ok` takes `Fut: Future<Output = ()> + Send + 'static`, and `smol::spawn` asks for the same. `'static` is there because the executor stores the task and nobody waits for the spawning function, so a future that borrows a local could outlive it: `pool.spawn_ok(async { names.len() })` fails with E0373 and rustc suggests `async move`. An `async fn` called with a reference has the same problem, because the returned future stores its arguments: `spawn_ok(greet(&cfg, user))` fails with E0597. `Send` is there because the pool may resume the task on a different worker after any `.await`. The fix is ownership: move owned values into an `async move` block, and share data through `Arc` clones, never `Rc`.

code

rust · 9 lines
rust
use futures::executor::ThreadPool;

fn main() {
    let pool = ThreadPool::new().unwrap();
    let names = vec!["ana".to_string(), "bo".to_string()];
    pool.spawn_ok(async {
        println!("{} users online", names.len());
    });
}

go deeper

for a junior

Recall the two bounds and what each protects: 'static because the task outlives the caller, Send because another worker thread may resume it. Know that async move and Arc clones are the everyday fixes.

for a middle

Explain that an async fn's future stores its arguments, so a reference parameter makes the future non-'static, and read E0373 and E0597 back to that cause instead of sprinkling move.

for a senior

Show that the bounds belong to the spawn API: a local executor drops Send, a scoped executor relaxes 'static, and a join on the current task needs neither, then pick the one that fits the data's ownership.

for a principal

Treat Send + 'static as a design constraint on handler signatures: owned arguments and Arc-shared state keep every handler spawnable, which matters when a team later moves work between executors.

## What spawning hands over **Spawning** gives a future to an executor and returns at once. The executor stores the future as a **task**, polls it whenever its waker fires, and keeps doing so after the spawning function has returned. Two facts follow, and each becomes a trait bound in the spawn function's signature: - the task can **outlive** the stack frame that created it, so it must not borrow anything from that frame; - on a **multi-threaded** executor, the task can be polled by one worker thread, suspend at an `.await`, and be resumed by another, so the whole future value must be safe to move between threads. In Rust these are `'static` and `Send`. They are not properties of async code in general; they are what a particular spawn API asks for. `futures::executor::ThreadPool::spawn_ok` declares `Fut: Future<Output = ()> + Send + 'static`; `smol::spawn` declares `impl Future<Output = T> + Send + 'static` with `T: Send + 'static` for the result, and Tokio's spawn has the same shape. ## The 'static half: borrowing the caller's locals An `async` block, like a closure, captures each variable it mentions in the least demanding mode its body allows, which for anything only read is **by reference**, unless the block is marked `move`. A block that only reads a local `Vec` therefore holds `&Vec<String>`, and the future is only valid while that local lives. Passing it to `spawn_ok` produces **E0373**, "async block may outlive the current function, but it borrows `names`", with a note that "async blocks are not executed immediately" and a suggestion to add `move`. An `async fn` hides the same trap. Calling `greet(&cfg, user)` runs none of the body; it returns a future that stores **every argument**, including `&cfg`. The future's type now carries a borrow, so `spawn_ok(greet(&cfg, user))` fails with **E0597**: "argument requires that `cfg` is borrowed for `'static`", and the note points at the `'static` in the spawn signature. ## The Send half: crossing worker threads `Send` is an **auto trait**: the compiler implements it for a type when every part of that type is `Send`. A future produced by an `async` block or `async fn` is an anonymous type whose parts are its captured variables plus whatever it keeps alive across each `.await`. If any part is not `Send`, an `Rc` for example, the future is not `Send` and the spawn call fails with "future cannot be sent between threads safely". Which values count as kept across an `.await` is its own question; here it is enough that the spawn bound checks the entire future type. ## The fixes, in the order you reach for them 1. **Add `move`.** `async move { ... }` captures by value, so the future owns `names` and is `'static`. The caller can no longer use `names` afterwards. 2. **Clone before moving** when the caller still needs the value: `let names2 = names.clone();` then move `names2` in. 3. **Share with `Arc`** when the data is large or many tasks read it: clone the `Arc` and move the clone in. `Arc<T>` is `Send` when `T` is `Send + Sync`. 4. **Pass owned arguments** to an `async fn` you intend to spawn: take `Arc<Config>` or `String`, not `&Config` or `&str`. | bound | why the spawn API needs it | typical error when broken | |---|---|---| | `'static` | the task outlives the spawning frame | E0373 on an async block, E0597 on a borrowed argument | | `Send` | a worker thread other than the spawner may resume it | "future cannot be sent between threads safely" | `async move` fixes only the first row. It moves values into the future, but a moved-in `Rc` is still not `Send`, so ownership and thread safety are separate checks. ## Executors that ask for less The bounds belong to the API, so other executors relax them on purpose. `smol::LocalExecutor<'a>` (from async-executor) spawns `impl Future<Output = T> + 'a` with no `Send` bound, and it can only be run on the thread that created it. Its multi-threaded sibling `async_executor::Executor<'a>` keeps `Send` but replaces `'static` with `'a`, so a scoped executor can run futures that borrow data outliving it. Running several futures concurrently on the current task with a join needs no spawn and no `Send` or `'static` bound, because nothing outlives the caller. The same bounds show up in the threads material for `std::thread::spawn`'s closure; the async versions differ only in that the thing being moved is a future value that will be resumed later, possibly elsewhere.

  • Why does `pool.spawn_ok(greet(&cfg, user))` fail when no async block appears in the code?
    Calling an `async fn` runs none of its body; it returns a future that stores every argument, including the reference `&cfg`. That future's type borrows `cfg`, so it cannot satisfy the `'static` bound of `spawn_ok`, and rustc 1.99.1 reports E0597 with "argument requires that `cfg` is borrowed for `'static`". Change the parameter to an owned type such as `Arc<Config>` and pass a clone.
  • Why does `smol::spawn` also require the future's output type to be `Send + 'static`?
    The output is handed back through the returned `Task<T>`, which the caller may await on another thread and long after the spawning frame is gone. Its signature is `spawn<T: Send + 'static>(future: impl Future<Output = T> + Send + 'static)`. It asks for `Send` even though its global executor starts one thread unless `SMOL_THREADS` says otherwise, because the bound is the API's contract, not the current thread count.
  • Can any executor run a spawned future that borrows a local variable?
    Yes, when the executor's own lifetime is tied to the borrowed data. `async_executor::Executor<'a>` and `smol::LocalExecutor<'a>` spawn futures bounded by `'a` instead of `'static`, so an executor created inside a scope can run tasks that borrow values outliving that executor. A process-wide pool cannot, because its tasks may outlive any particular frame.

  • async move makes any future Send.
  • A 'static future has to keep running until the program exits.
  • Wrapping the shared config in an Rc fixes the spawn error.
  • Calling .clone() on a reference inside the async block removes the borrow.
  • Every Rust executor requires Send and 'static to spawn a future.
open as a page

A Rust chat server's handler locks a `std::sync::Mutex`, then awaits a broadcast; why does spawning it fail, and how do you fix it?

level: middleimportance: must knowfreq 80%

basics

~20 s

The handler's future stores every local that is alive at an .await, and std's MutexGuard is deliberately not Send, so the future is not Send and a multi-threaded spawn rejects it. Release the guard in an inner block before awaiting.

open as a page

When rustc decides whether an `async fn`'s future is `Send`, which values does it count as held across an `.await`?

level: middleimportance: should knowfreq 55%

basics

~20 s

The future holds every argument of the async fn, every local whose scope spans an .await even if never used again, temporaries alive at the await, and the future being awaited. One non-Send value among them makes it non-Send.

open as a page

In Rust, why is `match topics.lock().unwrap().get(&room).cloned() { Some(t) => notify(t).await, None => {} }` not `Send`, despite cloning the value out?

level: seniorimportance: should knowfreq 40%

basics

~20 s

The MutexGuard returned by lock().unwrap() is a temporary in the match scrutinee, and such temporaries live until the match has finished. The guard is therefore still alive at notify(t).await, which makes the future not Send even though t is an owned clone.

open as a page

For a latency-sensitive Rust service, how do you choose between a work-stealing multi-threaded executor requiring `Send` futures and thread-per-core local executors accepting `!Send` ones?

level: principalimportance: should knowfreq 30%

basics

~20 s

Default to a work-stealing executor with Send futures: it balances uneven load and fits most libraries. Choose thread-per-core local executors only when measurements show cross-thread synchronisation dominates and the work can be sharded evenly, accepting Rc-based state and manual balancing.

open as a page