锈并发与加入和杰里*李*刘易

0

的问题

我试图运行两个平行功能 join.

我的代码是简单的:

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

但无论我做什么,这需要4s—2s + 2s—,同时它应该采取2s如果我没有记错的话:

start: 37ns
end: 4.01036111s

有什么东西是我的失踪?

async-await asynchronous rust rust-tokio
2021-11-22 21:08:44
1

最好的答案

1

你打电话的性传播疾病睡觉功能把OS螺纹睡觉,你的节目上运行。 如果你打电话的 tokio::time::sleep 功能而不是,将来应进行评估,同时进行。

使实际的并行执行,则需要使用 tokio::task::spawn 让运行时决定哪线的运行产生了未来。

进一步阅读什么阻挡,我建议这个优秀的博客的员额: https://ryhl.io/blog/async-what-is-blocking/

2021-11-22 21:16:29

我看到...所以一旦我们进入异步与东京,我们必须要依靠它的所有异步的工作。 我会看看这个链接,非常感谢。
miravelardo

其他语言

此页面有其他语言版本

Русский
..................................................................................................................
Italiano
..................................................................................................................
Polski
..................................................................................................................
Română
..................................................................................................................
한국어
..................................................................................................................
हिन्दी
..................................................................................................................
Français
..................................................................................................................
Türk
..................................................................................................................
Česk
..................................................................................................................
Português
..................................................................................................................
ไทย
..................................................................................................................
Español
..................................................................................................................
Slovenský
..................................................................................................................