Join futures with limited concurrency

前端 未结 1 1196
我寻月下人不归
我寻月下人不归 2021-01-13 01:09

I have a large vector of Hyper HTTP request futures and want to resolve them into a vector of results. Since there is a limit of maximum open files, I want to limit concurre

相关标签:
1条回答
  • 2021-01-13 01:45

    We've used code like this in a project to avoid opening too many TCP sockets. These futures have Hyper futures within, so it seems exactly the same case.

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

    This is used in a piece of example code, so the event loop (core) is explicitly driven. Watching the number of file handles used by the program showed that it was capped. Additionally, before this bottleneck was added, we quickly ran out of allowable file handles, whereas afterward we did not.

    0 讨论(0)
提交回复
热议问题