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

JoinSet random order of completition

We can combine several tasks in a JoinSet and then we can calle join_all to wait for all of them to finish that might be in any order.

#[tokio::main]
async fn main() {
    simple_logger::SimpleLogger::new().init().unwrap();
    log::info!("Start");
    let mut tasks = tokio::task::JoinSet::new();

    tasks.spawn(async move {
        log::info!("Task long starts");
        tokio::time::sleep(tokio::time::Duration::from_secs(2)).await;
        log::info!("Task long is done");
    });
    std::thread::sleep(std::time::Duration::from_secs(1));
    log::info!("Long task started");

    for i in 0..5 {
        let time = rand::random::<u64>() % 100;
        log::info!("Task {i} setup for {time}");
        tasks.spawn(async move {
            log::info!("Task {i} starts");
            tokio::time::sleep(tokio::time::Duration::from_millis(time)).await;
            log::info!("Task {i} is done");
        });
    }

    log::info!("All tasks started");
    std::thread::sleep(std::time::Duration::from_secs(1));
    log::info!("Wait done");

    tasks.join_all().await;
    log::info!("End");
}
2025-09-17T12:07:02.366Z INFO  [demo] Start
2025-09-17T12:07:02.366Z INFO  [demo] Task long starts
2025-09-17T12:07:03.366Z INFO  [demo] Long task started
2025-09-17T12:07:03.366Z INFO  [demo] Task 0 setup for 95
2025-09-17T12:07:03.366Z INFO  [demo] Task 1 setup for 87
2025-09-17T12:07:03.366Z INFO  [demo] Task 2 setup for 97
2025-09-17T12:07:03.366Z INFO  [demo] Task 3 setup for 77
2025-09-17T12:07:03.366Z INFO  [demo] Task 4 setup for 87
2025-09-17T12:07:03.366Z INFO  [demo] All tasks started
2025-09-17T12:07:03.366Z INFO  [demo] Task 0 starts
2025-09-17T12:07:03.366Z INFO  [demo] Task 1 starts
2025-09-17T12:07:03.366Z INFO  [demo] Task 3 starts
2025-09-17T12:07:03.366Z INFO  [demo] Task 4 starts
2025-09-17T12:07:03.366Z INFO  [demo] Task 2 starts
2025-09-17T12:07:03.445Z INFO  [demo] Task 3 is done
2025-09-17T12:07:03.454Z INFO  [demo] Task 4 is done
2025-09-17T12:07:03.454Z INFO  [demo] Task 1 is done
2025-09-17T12:07:03.463Z INFO  [demo] Task 0 is done
2025-09-17T12:07:03.465Z INFO  [demo] Task 2 is done
2025-09-17T12:07:04.366Z INFO  [demo] Wait done
2025-09-17T12:07:04.367Z INFO  [demo] Task long is done
2025-09-17T12:07:04.367Z INFO  [demo] End
[package]
name = "demo"
version = "0.1.0"
edition = "2024"

[dependencies]
log = "0.4.28"
rand = "0.9.2"
simple_logger = "5.0.0"
tokio = { version = "1.47.1", features = ["full"] }