rust - 如何并行运行多个调用 thread::sleep 的期货?
问题描述
我有一个缓慢的未来,在运行完成之前会阻塞 1 秒钟。
我尝试使用join
组合器,但复合my_app
期货按顺序执行期货:
#![feature(pin, futures_api, arbitrary_self_types)]
extern crate futures; // v0.3
use futures::prelude::*;
use futures::task::Context;
use std::pin::PinMut;
use std::{thread, time};
use futures::executor::ThreadPoolBuilder;
struct SlowComputation {}
impl Future for SlowComputation {
type Output = ();
fn poll(self: PinMut<Self>, _cx: &mut Context) -> Poll<Self::Output> {
let millis = time::Duration::from_millis(1000);
thread::sleep(millis);
Poll::Ready(())
}
}
fn main() {
let fut1 = SlowComputation {};
let fut2 = SlowComputation {};
let my_app = fut1.join(fut2);
ThreadPoolBuilder::new()
.pool_size(5)
.create()
.expect("Failed to create threadpool")
.run(my_app);
}
为什么会这样join
工作?我预计未来会在不同的线程上产生。
实现目标的正确方法是什么?
货物.toml:
[dependencies]
futures-preview = "0.3.0-alfa.6"
结果:
$ time target/debug/futures03
real 0m2.004s
user 0m0.000s
sys 0m0.004s
解决方案
如果将 future 与它们结合起来,join()
它们将被转换为一个任务,在单个线程上运行。
如果 future 表现良好,它们将以事件驱动(异步)的方式并行运行。您会希望您的应用程序休眠 1 秒。
但不幸的是,你实现的未来并不乖巧。它阻塞当前线程一秒钟,不允许在此期间完成任何其他工作。因为期货在同一个线程上运行,所以它们不能同时运行。您的应用程序将休眠 2 秒。
请注意,如果您将示例更改为以下内容,则期货将保持独立的任务,您可以在线程池上并行独立运行它们:
fn main() {
let fut1 = SlowComputation {};
let fut2 = SlowComputation {};
let mut pool = ThreadPoolBuilder::new()
.pool_size(5)
.create()
.expect("Failed to create threadpool");
pool.spawn(fut1);
pool.run(fut2);
}
非常不鼓励编写阻塞主线程的期货,在实际应用程序中,您可能应该使用库提供的计时器,例如tokio::timer::Delay
或tokio::timer::timeout::Timeout
.
推荐阅读
- python - 来自 HTMLParser 的 Python 可覆盖函数
- webpack - 强制纱线将某些模块安装到给定的工作区,而不是将它们移动到monorepo的共享节点模块?
- tensorflow - 大型数据集的多标签损失函数
- php - 路线 [删除博客] 未定义。(查看:C:\xampp\htdocs\laravel\resources\views\blogs\blog.blade.php)错误
- ios - 不可访问时,UserDefaults 是否返回默认值或 nil?
- php - WooCommerce 如何自定义显示的订单字段的默认内容?
- python - 导入错误:ApacheBeam 上没有名为“google.cloud”的模块
- c# - 带有谷歌驱动 API OAuth 2.0 的 Asp.net MVC 在生产中不起作用
- java - 我如何将json映射到java中
- c++ - C++ 结构错误“调用‘擦除’没有匹配函数