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}");
}
}
Create a free account and build your private vault. Share publicly whenever you want.