Skip to content
Snippets Groups Projects
Verified Commit 2f69f0e7 authored by Jeremy Soller's avatar Jeremy Soller
Browse files

Add simple semaphore implementation using futex

parent 79452dbd
No related branches found
No related tags found
No related merge requests found
pub mod mutex; pub mod mutex;
pub mod once; pub mod once;
pub mod semaphore;
pub use self::{ pub use self::{
mutex::{Mutex, MutexGuard}, mutex::{Mutex, MutexGuard},
once::Once, once::Once,
semaphore::Semaphore,
}; };
use crate::platform::{types::*, Pal, Sys}; use crate::platform::{types::*, Pal, Sys};
......
// From https://www.remlab.net/op/futex-misc.shtml
//TODO: improve implementation
use crate::platform::{types::*, Pal, Sys};
use super::AtomicLock;
use core::sync::atomic::Ordering;
pub struct Semaphore {
lock: AtomicLock,
}
impl Semaphore {
pub const fn new(value: c_int) -> Self {
Self {
lock: AtomicLock::new(value),
}
}
pub fn post(&self) {
self.lock.fetch_add(1, Ordering::Relaxed);
self.lock.notify_one();
}
pub fn wait(&self) {
let mut value = 1;
loop {
match self.lock.compare_exchange_weak(
value,
value - 1,
Ordering::Acquire,
Ordering::Relaxed
) {
Ok(ok) => return,
Err(err) => {
value = err;
}
}
if value == 0 {
self.lock.wait_if(0);
value = 1;
}
}
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment