Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Count in parallel with random sleep

TODO: It was mentioned to me that rand is blocking and thus this code is problematic. I need to understand that better and update the example if necessary.


#[tokio::main]
async fn main() {
    println!("Start");
    tokio::join!(
        count("a", 10),
        count("b", 10),
    );
    println!("End");
}

async fn count(which: &str, n: u32) {
    for i in 0..n {
        print(which,i).await;
    }
}


async fn print(which: &str, n: u32) {
    let random_int = rand::random::<u64>() % 11;
    tokio::time::sleep(tokio::time::Duration::from_millis(random_int)).await;
    println!("{which} {n} random: {random_int}");
}
[package]
name = "demo"
version = "0.1.0"
edition = "2024"

[dependencies]
rand = "0.9.2"
tokio = { version = "1.47.1", features = ["full"] }