multithreading - 产生线程并获得 future 结果的最佳方法是什么?

标签 multithreading rust future

这个问题在这里已经有了答案:





What is the best approach to encapsulate blocking I/O in future-rs?

(1 个回答)


2年前关闭。




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

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

最佳答案

tokio::task::spawn_blocking是我一直在寻找的。

关于multithreading - 产生线程并获得 future 结果的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61193894/

相关文章:

c# - 允许工作线程在主线程显示对话框时工作

rust - 原地插入 Rust 数组,将其他元素向下推

rust - 跨闭包执行缓存结果 : the size for values of type `dyn Fn(u64) -> ...` cannot be known at compilation time

rust - 为什么在使用 TryFuture 而不是等效的 Future 时会收到有关类型不匹配的错误?

java - 如何保持固定大小的 ListenableFuture 池?

c# - 如何在 Winform 中使用多线程?

java - Spring中@Scheduled方法中的Thread.sleep

multithreading - 在 Rust 的线程中从闭包内传播错误

java - ExecutorCompletionService 挂起

android - AsyncTask 在线程完成之前不调用 onPreExecute