Home > Back-end >  Rust concurrency with join and tokio
Rust concurrency with join and tokio

Time:11-24

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:

start: 37ns
end: 4.01036111s

Is there something I'm missing?

CodePudding user response:

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/

  • Related