我们在一个项目中使用了这样的代码来避免打开太多的 TCP 套接字。这些期货包含 Hyper 期货,因此看起来完全相同。
// Convert the iterator into a `Stream`. We will process
// `PARALLELISM` futures at the same time, but with no specified
// order.
let all_done =
futures::stream::iter(iterator_of_futures.map(Ok))
.buffer_unordered(PARALLELISM);
// Everything after here is just using the stream in
// some manner, not directly related
let mut successes = Vec::with_capacity(LIMIT);
let mut failures = Vec::with_capacity(LIMIT);
// Pull values off the stream, dividing them into success and
// failure buckets.
let mut all_done = all_done.into_future();
loop {
match core.run(all_done) {
Ok((None, _)) => break,
Ok((Some(v), next_all_done)) => {
successes.push(v);
all_done = next_all_done.into_future();
}
Err((v, next_all_done)) => {
failures.push(v);
all_done = next_all_done.into_future();
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是在一段示例代码中使用的,因此事件循环 ( core) 是显式驱动的。观察程序使用的文件句柄数表明它已被封顶。此外,在添加此瓶颈之前,我们很快就用完了允许的文件句柄,而后来却没有。