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 concurrency with join and tokio

I am trying to run two functions in parallel with join.

My code is simple:

tokio = { version = "1.14.0", features = ["full"] }
use tokio::join;
use std::thread::sleep;
use std::time::{Duration, Instant};

async fn fn_1() -> i8 {
  sleep(Duration::from_secs(2));

  2
}

async fn fn_2() -> i8 {
  sleep(Duration::from_secs(2));

  1
}

#[tokio::main]
async fn main() -> () {
  let now = Instant::now();

  println!("start: {:#?}", now.elapsed());

  let a = fn_1();
  let b = fn_2();

  join!(a, b);

  println!("end: {:#?}", now.elapsed());
}

But no matter what I do, this takes 4s —2s + 2s—, while it should take 2s if I’m not mistaken:

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

start: 37ns
end: 4.01036111s

Is there something I’m missing?

>Solution :

You’re calling the std’s sleep functions which put the OS thread to sleep that your program is running on. If you call the tokio::time::sleep functions instead, the futures should be evaluated concurrently.

To enable actual parallelism in execution, you’ll need to use tokio::task::spawn to let the runtime decide which thread to run the spawned future on.

For further reading on what blocking is, I recommend this excellent blog post:
https://ryhl.io/blog/async-what-is-blocking/

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