Browse Source

Initial structure

master
Julio Biason 3 months ago
commit
841347f14f
  1. 1
      .gitignore
  2. 7
      Cargo.lock
  3. 6
      Cargo.toml
  4. 37
      src/lib.rs

1
.gitignore vendored

@ -0,0 +1 @@
/target

7
Cargo.lock generated

@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "beacon"
version = "0.1.0"

6
Cargo.toml

@ -0,0 +1,6 @@
[package]
name = "beacon"
version = "0.1.0"
edition = "2021"
[dependencies]

37
src/lib.rs

@ -0,0 +1,37 @@
//! A Semaphore-like structure.
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::sync::Condvar;
use std::sync::Mutex;
pub struct Beacon {
lock: Mutex<AtomicUsize>,
guard: Condvar,
}
impl Beacon {
pub fn new(leases: usize) -> Self {
Self {
lock: Mutex::new(AtomicUsize::new(leases)),
guard: Condvar::new(),
}
}
pub fn acquire(&self, leases: usize) {
let mut control = self.lock.lock().unwrap();
let mut current_leases = control.load(Ordering::Relaxed);
while current_leases < leases {
control = self.guard.wait(control).unwrap();
current_leases = control.load(Ordering::Relaxed);
}
control.fetch_sub(leases, Ordering::SeqCst);
}
pub fn release(&self, leases: usize) {
let control = self.lock.lock().unwrap();
control.fetch_add(leases, Ordering::SeqCst);
self.guard.notify_all();
}
}
Loading…
Cancel
Save