限制 join_all!() 中的并发期货数量
Limiting the number of concurrent futures in join_all!()
如何让 Rust 执行所有给定的期货(如 join_all!
)限制一次执行 10 个期货?
我需要从大量服务器下载文件,但同时查询不超过 10 个服务器(以准确测量它们的超时时间:如果我一次查询太多服务器,它们会超时,即使服务器由他们自己很快)。
您可以使用 futures
crate 通过创建一个 futures 流来做到这一点(例如,使用 futures::stream::iter
) and call buffered
or buffer_unordered
最多执行 n 个 futures并行。
use futures::prelude::*;
// create an iterator of futures to execute
let futures =
(0..50).map(|n| async move {
fetch(format!("https://server-{}.example.com", n)).await
});
// create a buffered stream that will execute up to 10 futures in parallel
// (without preserving the order of the results)
let stream = futures::stream::iter(futures).buffer_unordered(10);
// wait for all futures to complete
let results = stream.collect::<Vec<_>>().await;
如何让 Rust 执行所有给定的期货(如 join_all!
)限制一次执行 10 个期货?
我需要从大量服务器下载文件,但同时查询不超过 10 个服务器(以准确测量它们的超时时间:如果我一次查询太多服务器,它们会超时,即使服务器由他们自己很快)。
您可以使用 futures
crate 通过创建一个 futures 流来做到这一点(例如,使用 futures::stream::iter
) and call buffered
or buffer_unordered
最多执行 n 个 futures并行。
use futures::prelude::*;
// create an iterator of futures to execute
let futures =
(0..50).map(|n| async move {
fetch(format!("https://server-{}.example.com", n)).await
});
// create a buffered stream that will execute up to 10 futures in parallel
// (without preserving the order of the results)
let stream = futures::stream::iter(futures).buffer_unordered(10);
// wait for all futures to complete
let results = stream.collect::<Vec<_>>().await;