Sub topic 14
Composing futures: join, select, and spawn
This chapter assumes you have read the earlier chapters on Poll, Waker, Pin, and block_on. You should also know how Arc and threads work. Here you will see how several futures run inside one program: combined in a single task with join or select, or given their own task with spawn.
Sequential `.await` runs one future at a time
Two .await expressions in a row do not overlap. The second future is not polled until the first one returns Ready.
async fn sequential() {
let a = fetch_a().await; // fetch_b has not started yet
let b = fetch_b().await;
println!("{a} {b}");
}
# async fn fetch_a() -> u32 { 1 }
# async fn fetch_b() -> u32 { 2 }To overlap I/O waits, you need a future that polls several children. That combinator is itself a future, so it fits anywhere an async fn result fits.
Join: wait for all
A join future holds every child future. Each time the executor polls it, it polls each unfinished child, stores any finished results, and returns Ready only when all children are done.
The sketch below uses std::future::poll_fn, which turns a closure into a future. It also uses pin! from the pinning chapter, because children must stay pinned between polls.
use std::future::{poll_fn, Future};
use std::pin::pin;
use std::task::Poll;
async fn join2<A, B>(a: A, b: B) -> (A::Output, B::Output)
where
A: Future,
B: Future,
{
let mut a = pin!(a);
let mut b = pin!(b);
let mut a_out = None;
let mut b_out = None;
poll_fn(|cx| {
if a_out.is_none() {
if let Poll::Ready(v) = a.as_mut().poll(cx) {
a_out = Some(v);
}
}
if b_out.is_none() {
if let Poll::Ready(v) = b.as_mut().poll(cx) {
b_out = Some(v);
}
}
if a_out.is_some() && b_out.is_some() {
Poll::Ready((a_out.take().unwrap(), b_out.take().unwrap()))
} else {
Poll::Pending
}
})
.await
}Three details matter here:
- A finished child is never polled again. Polling a future after it returned
Readymay panic or misbehave. - Both children receive the same
Context. Either child's waker wakes the whole join future, so the next poll re-checks every unfinished child. - Everything runs on one thread inside one task. The children interleave only at their
.awaitpoints. They never run in parallel.
In real code you would use tokio::join! or futures::join!. They do the same work for any number of children without heap allocation. For a list whose length is known only at runtime, use futures::future::join_all or tokio::task::JoinSet.
Select: first one wins
Select also polls several children, but it returns as soon as one is Ready. The other children are dropped.
use std::future::{poll_fn, Future};
use std::pin::pin;
use std::task::Poll;
enum Either<L, R> {
Left(L),
Right(R),
}
async fn select2<A, B>(a: A, b: B) -> Either<A::Output, B::Output>
where
A: Future,
B: Future,
{
let mut a = pin!(a);
let mut b = pin!(b);
poll_fn(|cx| {
if let Poll::Ready(v) = a.as_mut().poll(cx) {
return Poll::Ready(Either::Left(v));
}
if let Poll::Ready(v) = b.as_mut().poll(cx) {
return Poll::Ready(Either::Right(v));
}
Poll::Pending
})
.await
}When select2 returns, a and b go out of scope. The loser is dropped mid-execution, which is cancellation as described in the next chapter. Note the fixed order: if both are ready on the same poll, a always wins. Macros such as tokio::select! randomize the order by default to avoid starving later branches.
Typical uses of select are timeouts, shutdown signals, and racing replicas of the same request.
Spawn: give a future its own task
Join and select keep all children inside the caller's task. spawn instead hands a future to the runtime as a new, independent task. The runtime schedules it separately, and on a multi-threaded runtime it may run on another thread.
The example needs Tokio. Add this to Cargo.toml:
[dependencies]
tokio = { version = "1", features = ["full"] }use std::time::Duration;
use tokio::time::sleep;
#[tokio::main]
async fn main() {
let handle = tokio::spawn(async {
sleep(Duration::from_millis(50)).await;
21 * 2
});
let (a, b) = tokio::join!(
async {
sleep(Duration::from_millis(30)).await;
"a"
},
async {
sleep(Duration::from_millis(30)).await;
"b"
},
);
let n = handle.await.unwrap();
println!("{a} {b} {n}");
}The two join! branches finish in about 30 ms total, not 60 ms, because their timers overlap. The spawned task makes progress during that time without anyone awaiting it. handle.await returns Result<T, JoinError>, because the task may have panicked or been aborted.
What spawn requires
tokio::spawn has stricter bounds than join!:
'static: The task may outlive the function that spawned it, so it cannot borrow local variables. Useasync moveand give it owned data or anArc.Send: On a multi-threaded runtime, a task can move between worker threads, so everything held across an.awaitmust beSend. The later chapter onSendbounds covers this.
join! and select! need neither bound, because the children are polled in place. They can borrow from the surrounding function.
Choosing between them
| Need | Use | Runs in parallel? | Borrowing allowed? |
|---|---|---|---|
| Overlap waits, need every result | `join!` | No, one task | Yes |
| Take the first result, cancel the rest | `select!` | No, one task | Yes |
| Independent work that outlives the caller | `spawn` | Yes, on a multi-threaded runtime | No, needs `'static` |
| CPU-heavy work in the same task | Neither. Use `spawn_blocking` or a thread pool | Yes | Depends |
Because join keeps all children in one task, a child that does a long synchronous computation stalls its siblings. They share one thread of execution until the next .await. Spawning moves a child to its own task, so another worker thread can run it.
Common errors
- Dropping a
JoinHandledoes not cancel the task. The task keeps running detached. To stop it, callhandle.abort(). - Awaiting spawned handles one by one is fine. The tasks already run concurrently, so awaiting in order does not serialize them.
- A panic in one
join!branch unwinds through the whole join, and the other branches are dropped. A panic in a spawned task is caught by the runtime and reported asErr(JoinError)from the handle. - A
select!in a loop recreates its futures on every iteration unless you pin and reuse them. A timer created inside the loop restarts each time.
Exercise
In select2(a, b) above, a is a future that has already made partial progress, and b becomes ready first. What happens to a, and what does this imply about which futures are safe to pass to select?
Show answer
When select2 returns, a is dropped at its current await point, so it is cancelled and never resumes. Any partially completed work is lost, for example bytes it had read but not yet returned. Only futures that are cancellation safe, where dropping between polls loses nothing, should be raced this way. Otherwise pin the future outside the select, so that dropping the select does not drop the future, and poll it again later.
Exercise
A function takes &str and wants to run two lookups that borrow it at the same time. Can it use tokio::spawn for both lookups? What can it use instead?
Show answer
No. tokio::spawn requires a 'static future, and a borrow of the local &str is not 'static. It can use tokio::join! (or futures::join!) on the two lookup futures, because join polls the children inside the current task and allows borrows. Alternatively, it can copy the string into an owned String or Arc<str> and spawn with async move.