typestar

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

  1. Each branch is a future and the code to run when it wins.
  2. The losing futures are dropped, canceling them.
  3. timeout wraps the same idea in one call.

Keywords and builtins used here

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.

Type this snippet

Step 4 of 6 in Async with tokio, step 12 of 15 in Concurrency & async.

← Previous Next →