【问题标题】:What is the best way to spawn a thread and obtain the result as a future? [duplicate]产生线程并获得未来结果的最佳方法是什么? [复制]
【发布时间】:2020-07-26 08:47:47
【问题描述】:

有没有更好的方法来做类似下面的事情?

use futures::channel::oneshot; // 0.3.4
use std::thread;

pub async fn spawn<Y>(f: impl Fn() -> Y + Send + Sync + 'static) -> Y
where
    Y: Send + 'static,
{
    let (sender, receiver) = oneshot::channel::<Y>();
    thread::spawn(move || sender.send(f()));
    receiver.await.unwrap()
}

【问题讨论】:

标签: multithreading rust future


【解决方案1】:

tokio::task::spawn_blocking 是我要找的。​​p>

【讨论】:

  • 请不要回答重复的问题。相反,您可以选择将它们标记为重复项(此时我们已经这样做了)。
猜你喜欢
  • 1970-01-01
  • 2019-07-15
  • 2019-10-12
  • 1970-01-01
  • 1970-01-01
  • 2017-11-28
  • 1970-01-01
  • 2017-11-16
  • 1970-01-01
相关资源
最近更新 更多