select! and timeouts in Rust
select! takes whichever future finishes first — the shape of every timeout.
use tokio::time::{sleep, timeout, Duration};
async fn slow() -> &'static str {
sleep(Duration::from_millis(200)).await;
"slow finished"
}
#[tokio::main]
async fn main() {
tokio::select! {
result = slow() => println!("{result}"),
_ = sleep(Duration::from_millis(50)) => println!("gave up first"),
}
match timeout(Duration::from_millis(50), slow()).await {
Ok(value) => println!("{value}"),
Err(_) => println!("timed out"),
}
}
How it works
- Each branch is a future and the code to run when it wins.
- The losing futures are dropped, canceling them.
timeoutwraps the same idea in one call.
Keywords and builtins used here
ErrOkasyncawaitfnmainmatchslowstaticstruse
The run, in numbers
- Lines
- 19
- Characters to type
- 428
- Tokens
- 135
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 74 seconds.
Step 4 of 6 in Async with tokio, step 12 of 15 in Concurrency & async.