use std::sync::{Arc, Condvar, Mutex};
pub struct Semaphore {
inner: Arc<Inner>,
}
struct Inner {
count: Mutex<usize>,
cvar: Condvar,
}
impl Semaphore {
pub fn new(capacity: usize) -> Self {
Semaphore {
inner: Arc::new(Inner {
count: Mutex::new(capacity),
cvar: Condvar::new(),
}),
}
}
pub fn acquire(&self) {
let mut count = self.inner.count.lock().unwrap();
while *count == 0 {
count = self.inner.cvar.wait(count).unwrap();
}
*count -= 1;
}
pub fn release(&self) {
let mut count = self.inner.count.lock().unwrap();
*count += 1;
self.inner.cvar.notify_one();
}
}