expression
Owned permits for spawned tasks
An owned permit can travel with a spawned task, holding the shared semaphore alive. Acquire before spawning when the admission limit should also bound the number of admitted tasks. Release on task exit. Tokio is an external dependency; see the proposed Cargo manifest. Expected stdout (not executed): 21 1 Common mistake: Spawning an unbounded number of tasks that all wait for permits inside their bodies.
Formal Syntax & Structure
rust syntaxrust
Arc<Semaphore>::acquire_owned().awaitWorking Example
Example Snippetrust
#[tokio::main(flavor = "current_thread")]async fn main() { use std::sync::Arc; let sem = Arc::new(tokio::sync::Semaphore::new(1)); let permit = sem.clone().acquire_owned().await.unwrap(); let task = tokio::spawn(async move { let _permit = permit; 21 }); println!("{}", task.await.unwrap()); println!("{}", sem.available_permits());}