-
I want to limit the number of in-flight tasks at a given point in time. Given a setup where I create a task for each line in a file (e.g. say each line is a url in the file)
But this will create as many tasks as number of urls. Say I want to limit to only 100 urls being processed at a time. My first attempt is to use a semaphore
This works at limiting the number of |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
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. |
Beta Was this translation helpful? Give feedback.
Try
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.