Sub topic 10
Running futures concurrently with join! and select!
This chapter assumes you can write async fn, use .await, and start a Tokio runtime with #[tokio::main]. It also assumes you know that futures do nothing until they are polled. Here you will learn how to run several futures at the same time. You will also learn how to stop waiting when the first of them finishes.
Sequential awaits are not concurrent
Awaiting two futures one after the other runs them one after the other. The second future is not polled until the first one completes.
use std::time::{Duration, Instant};
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 start = Instant::now();
let a = work(1, 200).await;
let b = work(2, 100).await;
println!("{a} {b} after {} ms", start.elapsed().as_millis());
}This prints 1 2 after 300 ms or slightly more. The waits add up, although the program does nothing during them.
join!: wait for all
tokio::join! takes several futures and polls all of them from one place. It completes when every future has completed. It returns a tuple of the outputs, in the order you wrote the futures.
use std::time::{Duration, Instant};
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 start = Instant::now();
let (a, b) = tokio::join!(work(1, 200), work(2, 100));
println!("{a} {b} after {} ms", start.elapsed().as_millis());
}The output is 1 2 after 200 ms, give or take a few milliseconds. The total wait is the longest single wait. The result order follows the argument order, not the finishing order. Future 2 finishes first, but its value is still second in the tuple.
Concurrent is not parallel
join! does not create tasks. All its futures live inside the one future that contains the join! call, so they are polled on one thread at a time. This works well when the futures spend their time waiting on timers, sockets, or channels. It does not help when they compute.
If one branch blocks the thread, for example with std::thread::sleep, every branch stalls. The join! branches share one thread of execution. If you want true parallelism across worker threads, use tokio::spawn and join the handles.
try_join!: stop at the first error
When the futures return Result, tokio::try_join! completes as soon as one of them returns Err. The other futures are dropped, which cancels them. All the futures must have the same error type.
use tokio::try_join;
async fn parse(s: &str) -> Result<i32, std::num::ParseIntError> {
s.parse::<i32>()
}
#[tokio::main]
async fn main() {
match try_join!(parse("10"), parse("abc")) {
Ok((a, b)) => println!("{a} {b}"),
Err(e) => println!("failed: {e}"),
}
}This prints failed: invalid digit found in string. If both succeed, you get Ok with a tuple of the values.
select!: wait for the first
tokio::select! polls several futures and finishes as soon as one completes. It runs the handler for that branch. It then drops all the other futures.
use std::time::Duration;
use tokio::time::sleep;
#[tokio::main]
async fn main() {
tokio::select! {
_ = sleep(Duration::from_millis(100)) => println!("fast timer won"),
_ = sleep(Duration::from_millis(500)) => println!("slow timer won"),
}
}This prints fast timer won. Each branch has the form pattern = future => handler. The loser is cancelled by being dropped, as the previous chapter on cancellation described.
By default select! picks randomly among branches that are ready at the same moment, which avoids starving later branches. Add biased; as the first line inside the macro to poll branches in the order written.
select! in a loop
A common use is an event loop that reacts to messages until a deadline. The deadline future must be created once, outside the loop. If you wrote sleep(...) inside the select!, each iteration would create a fresh timer and the deadline would never arrive.
use tokio::sync::mpsc;
use tokio::time::{sleep, Duration};
#[tokio::main]
async fn main() {
let (tx, mut rx) = mpsc::channel::<u32>(8);
tokio::spawn(async move {
for i in 0..3 {
tx.send(i).await.unwrap();
sleep(Duration::from_millis(50)).await;
}
});
let deadline = sleep(Duration::from_millis(500));
tokio::pin!(deadline);
loop {
tokio::select! {
Some(v) = rx.recv() => println!("got {v}"),
_ = &mut deadline => {
println!("deadline");
break;
}
}
}
}The output is got 0, got 1, got 2, then deadline. Three details matter here:
tokio::pin!pins the timer in place. This lets you poll it again through&mut deadlineon every iteration, instead of moving it into the macro.rx.recv()returnsNoneafter the sender is dropped. The patternSome(v)does not matchNone, soselect!disables that branch for this call. The loop then waits only for the deadline.- If every branch is disabled and there is no
elsebranch,select!panics. Addelse => breakwhen a loop could run out of live branches.
Cancellation safety in select!
A branch that loses is dropped partway through its work. That is only harmless if the future is cancel safe, meaning that dropping it loses no data. mpsc::Receiver::recv is cancel safe. If it loses a race, no message is consumed.
Other operations are not. A read such as read_exact may have copied some bytes into your buffer when it is dropped. Those bytes are then gone from the stream. The Tokio documentation states the cancel-safety of each method, so check it before putting a method in a select! loop.
Choosing a tool
| Tool | Completes when | Result | Runs on |
|---|---|---|---|
| `join!` | All futures finish | Tuple of outputs | The current task |
| `try_join!` | All succeed, or one fails | `Result` of a tuple | The current task |
| `select!` | The first future finishes | The winning handler's value | The current task |
| `tokio::spawn` | The task finishes | `JoinHandle` to await | Any worker thread |
Use join! or select! when the number of futures is fixed and known when you write the code. If you have a variable number of futures, spawn tasks and collect the JoinHandles, or use futures::future::join_all.
Exercise
A program calls tokio::join!(a(), b()). The future a() calls std::thread::sleep(Duration::from_secs(1)), and b() awaits tokio::time::sleep(Duration::from_millis(10)). When does b() finish, and how would you fix the problem?
Show answer
b() cannot finish until a() returns, so it finishes after about one second. Both futures are polled on the same thread, and std::thread::sleep blocks that thread, so the timer for b() is not polled in the meantime. Replace the blocking call with tokio::time::sleep(...).await. For blocking work that cannot be made async, run it in tokio::task::spawn_blocking and await its handle.