加入限并发的期货

Pie*_*tro 7 rust

我有一个超 HTTP 请求期货的大向量,并希望将它们解析为结果向量。由于有最大打开文件的限制,我想将并发限制为N个期货。

我已经尝试过,Stream::buffer_unordered但似乎它一个一个地执行期货。

She*_*ter 5

我们在一个项目中使用了这样的代码来避免打开太多的 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) 是显式驱动的。观察程序使用的文件句柄数表明它已被封顶。此外,在添加此瓶颈之前,我们很快就用完了允许的文件句柄,而后来却没有。