How to dynamically add futures to run them concurrently

Im so confused here, if i wanna run 100 futures concurrently. I would simply use join all

#[tokio::main]
async fn main(){
 let mut v = Vec::new();
 for _ in 1..=100{
  v.push(do())
}
join_all(v).await;

}

async fn do(){
    tokio::time::sleep(Duration::from_secs(5)).await;
    println("Printed in 5 secs");
}

BUT, what if i want to dynamically add to that join all. I mean i want to dynamically add a new future during runtime inside of v and run that future concurrently. Idk, if what im saying is making sense or not, but something like a listening to a channel and whenever some future comes in that channel, run that future concurrently with other futures that came before, like a join all but during runtime by listening to some sort of channel. How do i do this? Help...

You can do this:

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

for next_task in list {
    while tasks.len() >= 10 {
        // Wait for a task to complete, then put away the output.
        // Ok to unwrap. We just checked that `tasks` is not empty.
        outputs.push(tasks.next().await.unwrap());
    }

    tasks.push(tokio::spawn(do(next_task)));
}

// Drain remaining tasks.
while let Some(output) = tasks.next().await {
    outputs.push(output);
}

There are also some other ways too using buffered or buffer_unordered from the futures crate.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.