Limit Async Concurrency with a Semaphore

Share a tokio semaphore across spawned tasks, hold a permit for each job, and collect every result with JoinSet.

RustResilience

Code

rustsnippet
28 lines
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::Semaphore;
use tokio::task::JoinSet;
use tokio::time::sleep;

#[tokio::main]
async fn main() {
    let limit = Arc::new(Semaphore::new(2));
    let mut tasks = JoinSet::new();

    for id in 0..6 {
        let permits = Arc::clone(&limit);
        tasks.spawn(async move {
            let _permit = permits.acquire_owned().await.expect("semaphore closed");
            sleep(Duration::from_millis(30)).await;
            id * id
        });
    }

    let mut results = Vec::new();
    while let Some(joined) = tasks.join_next().await {
        results.push(joined.expect("task panicked"));
    }
    results.sort_unstable();
    println!("{results:?}");
}

What the code does

Limit Async Concurrency with a Semaphore keeps everything in the function main.

Iteration happens inside for id in 0..6 — everything outside it runs once.

Caveats

  • Plan for an install step: tokio::sync::Semaphore, tokio::task::JoinSet and tokio::time::sleep are a real dependency, resolved by the package manager.

Statements that matter

while let Some(joined) = tasks.join_next().await {
results.push(joined.expect("task panicked"));
}
tasks.spawn(async move {
let _permit = permits.acquire_owned().await.expect("semaphore closed");
sleep(Duration::from_millis(30)).await;
id * id
});

Interactive Tools for This Topic

FAQ

Are there third-party dependencies?
`tokio::sync::Semaphore`, `tokio::task::JoinSet` and `tokio::time::sleep` — install them with the package manager before running.