Sub topic 9
Running futures concurrently with join! and select!
This chapter assumes you can write async fn, use .await, and start a Tokio runtime. You should also know that a future does nothing until it is polled.
Why awaiting in sequence is slow
Each .await pauses the current function until that future finishes. If you await two independent timers one after the other, their waits add up. To overlap them, you must hand both futures to one place that polls them together.
join!: wait for all
tokio::join! polls several futures at the same time within the current task. It finishes when every future has finished, and it returns their outputs as a tuple in the order you wrote them.
use std::time::Duration;
use tokio::time::sleep;
async fn work(id: u32, ms: u64) -> u32 {
sleep(Duration::from_millis(ms)).await;
id
}
#[tokio::main]
async fn main() {
let (a, b) = tokio::join!(work(1, 200), work(2, 100));
println!("{a} {b}");
}The total wait is about 200 ms, not 300 ms. The result order is 1 2, even though the second future finishes first.
select!: wait for the first
tokio::select! polls several futures and runs the branch of the first one to complete. It then drops all the other futures. Each branch has the form pattern = future => handler.
use std::time::Duration;
use tokio::time::sleep;
#[tokio::main]
async fn main() {
tokio::select! {
_ = sleep(Duration::from_millis(100)) => println!("short timer won"),
_ = sleep(Duration::from_millis(500)) => println!("long timer won"),
}
}This prints short timer won. The 500 ms timer is dropped before it finishes.
Concurrency is not parallelism
Futures inside one join! or select! all run on the same task, so they take turns on one thread at a time. This works well when they spend most of their time waiting. If one of them does heavy computation without an .await, the others cannot make progress. To get true parallelism, use tokio::spawn, which creates separate tasks that the runtime can schedule on different worker threads.
Common mistakes
- Forgetting that select! cancels. A dropped future stops at its last
.await. Any work it had started but not finished is lost, so avoidselect!on futures that are not safe to cancel. - Expecting join! to stop on error.
join!waits for everything. If you want to stop at the firstErr, usetokio::try_join!, which returns early with the first error. - Blocking inside a branch. A call like
std::thread::sleepstalls every future in the same task.
Exercise
You have two independent network requests that each take about 1 second. You await them one after the other. About how long does it take, and what single change makes it about 1 second?
Show answer
Awaiting in sequence takes about 2 seconds. Wrap both calls in tokio::join! so they are polled together, and the total wait becomes about 1 second.
Exercise
In a select! with two branches, the first branch completes. What happens to the future in the second branch, and why does that matter?
Show answer
It is dropped, which cancels it at its current .await. Any partial work it did is lost, so the future must be safe to cancel.