i would like to be able to tell tokio to run e.g.: 10 concurrent tasks at a time, and never run more than 10
the current code i am using
let futs = vec![];
for i in 0..100 {
let fut = tokio::spawn(async move { });
futs.push(fut);
if futs.len() == 10 {
let mut _futs = vec![];
_futs.append(&mut futs);
for fut in _futs { fut.await?; }
futs.clear();
}
}
as you can see in above, i wait for all the 10 tasks to finish before moving to the next 10, what i would like to do, is when a room exists, spawn the next task.. and so on, maintaining a limit of 10 tasks until all the tasks are finished.
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);
}