Rust

Concurrency Limit with Semaphore

admin by @admin ADMIN
Jun 15, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Fan out N tasks but limit how many run at once via `tokio::sync::Semaphore`. Standard pattern for HTTP fan-out where you must respect a server's rate limit.
Rust
Raw
use std::sync::Arc;
use tokio::sync::Semaphore;
use tokio::time::{sleep, Duration};

async fn do_work(id: u32, sem: Arc<Semaphore>) -> u32 {
    let _permit = sem.acquire().await.unwrap();      // blocks until a slot is free
    println!("[{id}] start");
    sleep(Duration::from_millis(200)).await;
    println!("[{id}] done");
    id * 10
}

#[tokio::main]
async fn main() {
    let sem = Arc::new(Semaphore::new(3));            // at most 3 in flight
    let handles: Vec<_> = (0..10).map(|i| {
        let sem = Arc::clone(&sem);
        tokio::spawn(do_work(i, sem))
    }).collect();

    for h in handles {
        let v = h.await.unwrap();
        println!("got {v}");
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.