Limit concurrent async tasks in Rust by acquiring a permit from a tokio::sync::Semaphore before entering a critical section.
Use tokio::sync::Semaphore to limit concurrent access to a resource by acquiring a permit before execution and releasing it afterward.
use tokio::sync::Semaphore;
#[tokio::main]
async fn main() {
let semaphore = Semaphore::new(3);
let permit = semaphore.acquire().await.unwrap();
// Critical section
drop(permit);
}
A semaphore acts like a ticket dispenser for a limited number of seats. It lets you control how many tasks can run at the same time by requiring them to grab a ticket before starting. Once a task finishes, it returns the ticket so another task can use it.