Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

rust 2 async functions synchronously, but start to continue to execute the code after the first finished and wait for the second function later

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; 
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading