How to Limit Concurrency in Async Rust (Semaphore)

Limit concurrent async tasks in Rust by using tokio::sync::Semaphore to acquire permits before execution.

Use tokio::sync::Semaphore to limit concurrent async tasks by acquiring a permit before execution. Add tokio to your Cargo.toml and wrap your async logic in a permit block to enforce the limit.

use tokio::sync::Semaphore;

#[tokio::main]
async fn main() {
    let semaphore = Semaphore::new(5);
    let mut handles = vec![];

    for _ in 0..100 {
        let sem = semaphore.clone();
        let handle = tokio::spawn(async move {
            let _permit = sem.acquire().await.unwrap();
            // Your async work here
        });
        handles.push(handle);
    }

    for handle in handles {
        handle.await.unwrap();
    }
}