【问题标题】:What is the difference between tokio::spawn(my_future).await and just my_future.await?tokio::spawn(my_future).await 和只是 my_future.await 有什么区别?
【发布时间】:2020-06-26 13:31:12
【问题描述】:

给定一个异步函数及其对应的未来,让我们说:

async fn foo() -> Result<i32, &'static str> {
    // ...
}

let my_future = foo();

仅使用 .await 等待它与使用 tokio::spawn().await 有什么区别?

// like this...
let result1 = my_future.await;

// ... and like this
let result2 = tokio::spawn(my_future).await;

【问题讨论】:

  • my_future.await 需要先完成,然后立即出现的任何代码才会运行。生成新任务将继续当前任务,同时在新任务中运行未来。

标签: rust rust-tokio


【解决方案1】:

通常不会等待生成的任务(或至少不会立即等待)。更常见的是简单写:

tokio::spawn(my_future);

省略.await,任务将在后台运行,而当前任务继续。立即调用.await 会阻止当前任务。 spawn(task).await 实际上与 task.await 没有什么不同。这类似于创建一个线程并立即加入它,这同样没有意义。

衍生任务不需要像裸期货那样等待。等待他们是可选的。那么,什么时候可能想要等待一个呢?如果您想要阻止当前任务直到生成的任务完成。

let task = tokio::spawn(my_future);

// Do something else.
do_other_work();

// Now wait for the task to complete, if it hasn't already.
task.await;

或者,如果您需要结果,但需要在开始任务和收集结果之间进行工作。

let task = tokio::spawn(my_future);

// Do something else.
do_other_work();

// Get the result.
let result = task.await;

【讨论】:

  • 我想我明白了。我认为两个未来(my_future 和 tokio::spawn 返回的未来)在等待之前什么都不做。我以为每一个未来都是懒惰的。我想我当时错了,你的解释很有意义!谢谢。
  • @hbobenicio 我今天也有同样的问题。看起来像 tokio::spawnthread::spawn,当你生成时,它会在后台运行。
猜你喜欢
  • 2022-06-19
  • 2010-10-07
  • 1970-01-01
  • 1970-01-01
  • 2021-08-25
  • 2017-12-30
  • 2012-03-20
  • 2022-01-21
相关资源
最近更新 更多