Tokio: number of concurrent tasks

The FuturesUnordered type is very useful for this, because it allows you to wait until one task has finished, and then lets you do some more work.

use futures::stream::StreamExt; // for next()

let mut futs = FuturesUnordered::new();
let mut outputs = Vec::new();

for i in 0..100 {
    let fut = async move { };
    futs.push(fut); // tokio::spawn is optional here

    if futs.len() == 10 {
        // this wont return None because futs is not empty
        outputs.push(futs.next().await.unwrap());
    }
}
// wait for remaining
while let Some(item) = futs.next().await {
    outputs.push(item);
}
5 Likes