Skip to content

Instantly share code, notes, and snippets.

@grantslatton
Created January 23, 2022 08:28
/// A basic semaphore that only allows a fixed number of
/// outstanding permits.
pub struct Semaphore {
remaining_permits: Arc<AtomicU64>,
}
impl Semaphore {
pub fn new(permits: u64) -> Self {
Self {
remaining_permits: Arc::new(AtomicU64::new(permits)),
}
}
/// Acquire a `Permit`, or return `None` if there are no available
/// permits.
pub fn try_acquire(&self) -> Option<Permit> {
// If we still have remaining permits, subtract one
// and vend a `Permit`.
if self.remaining_permits.load(Ordering::SeqCst) > 0 {
self.remaining_permits.fetch_sub(1, Ordering::SeqCst);
Some(Permit(Arc::clone(&self.remaining_permits)))
} else {
None
}
}
}
pub struct Permit(Arc<AtomicU64>);
/// Increment the remaining permits count on `drop`
impl Drop for Permit {
fn drop(&mut self) {
self.0.fetch_add(1, Ordering::SeqCst);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment