0

I want to run multiple async functions synchronously. I build a simple example for my problem. sleep1 should be executed at the beginning, but its requiered at a later point. sleep2 and sleep_arr should be executed before. Right now the code takes 8 seconds to complete but it should only take 5.

async fn test() -> bool {
    let sleep1 = sleep(5);
    let sleep2 = sleep(1).await;
    let sleep_arr = vec![sleep(2), sleep(2)];
    join_all(sleep_arr).await;
    sleep1.await;
    return true;
}
async fn sleep(sec: u64) -> () {
    use async_std::task;
    task::sleep(std::time::Duration::from_secs(sec)).await; 
}
1
  • I think your misconception here is that sleep(5) starts getting executed in line 1. It doesn't. Rust asyncs are lazy and only start once they get awaited. So the sleep(5) only starts to get executed at sleep1.await. Commented Jun 12, 2022 at 15:11

1 Answer 1

1

You can create an async block for the second sequence and then execute the two sequences that need to be executed in parallel using futures::join!:

async fn test() -> bool {
    let sleep1 = sleep(5);
    let task2 = async {
        let sleep2 = sleep(1).await;
        let sleep_arr = vec![sleep(2), sleep(2)];
        futures::future::join_all(sleep_arr).await;
    };
    futures::join!(sleep1, task2);
    return true;
}

async fn sleep(sec: u64) -> () {
    tokio::time::sleep(std::time::Duration::from_secs(sec)).await;
}

#[tokio::main]
async fn main() {
    let instant = std::time::Instant::now();
    test().await;
    dbg!(instant.elapsed());
}

Output:

[src/main.rs:20] instant.elapsed() = 5.001728234s

(I switched to tokio so it works in the playground but it should be the same with async_std.)

Playground

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.