Skip to content

Limit the number of in-flight tasks #2648

Answered by hawkw
kokil01 asked this question in General
Discussion options

You must be logged in to vote

Try

let sem = Arc::new(Semaphore::new(10));
for url in urls {
  let permit = Arc::clone(&sem).acquire_owned().await;
  task::spawn(async move {
    let _permit = permit;
    process_url(url).await;
  }
}

This way, the loop will wait until permits are available before spawning a new task, but the permits are not dropped until the spawned tasks complete.

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@kokil01
Comment options

@hawkw
Comment options

hawkw Jul 8, 2020
Maintainer

Answer selected by kokil01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
2 participants