2

Here is my code for trying tokio:

use std::{thread, time};
async fn one() -> i64 {
    let dur = time::Duration::from_secs(1);
    thread::sleep(dur);
    1
}

#[tokio::main(core_threads=3,max_threads=8)]
async fn main() {

    let ins1 = std::time::Instant::now();
    let a = one();
    let b = one();
    let (a, b) = futures::join!(a,b);
    println!("a+b: {:?}", a + b);
    let ins2 = std::time::Instant::now();
    let dur = ins2 - ins1;
    println!("time used: {:?}", dur);
}

I think a and b should run in parallel in different threads,so the output should be

a+b: 2
time used: 1.0s

but what I got is

a+b: 2
time used: 2.01022541s

My code runs on macOS Catalina with a 6Core i7 CPU.

Renkai
  • 1,991
  • 2
  • 13
  • 18
  • 2
    [Why you shouldn't use blocking code inside future ?](https://stackoverflow.com/questions/48735952/why-does-futureselect-choose-the-future-with-a-longer-sleep-period-first) – Ömer Erden Mar 08 '20 at 14:23
  • 3
    `std::thread::sleep` is blocking. If you want to sleep in paralel you should use ` tokio::time::Delay` – Svetlin Zarev Mar 08 '20 at 15:17

0 Answers0