Add a Mutex implementation.
This commit is contained in:
parent
71c6003905
commit
d1b5720abd
2 changed files with 83 additions and 0 deletions
|
|
@ -1,3 +1,7 @@
|
|||
use core::cell::UnsafeCell;
|
||||
use core::ops::Deref;
|
||||
use core::ops::DerefMut;
|
||||
|
||||
use crate::{cap::Capability, syscall, zion::ZError};
|
||||
|
||||
pub struct Semaphore {
|
||||
|
|
@ -17,3 +21,52 @@ impl Semaphore {
|
|||
syscall::semaphone_signal(&self.cap)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Mutex<T> {
|
||||
cap: Capability,
|
||||
data: UnsafeCell<T>,
|
||||
}
|
||||
|
||||
unsafe impl<T> Sync for Mutex<T> where T: Send {}
|
||||
|
||||
pub struct MutexGuard<'a, T> {
|
||||
mutex: &'a Mutex<T>,
|
||||
}
|
||||
|
||||
unsafe impl<T> Send for MutexGuard<'_, T> where T: Send {}
|
||||
unsafe impl<T> Sync for MutexGuard<'_, T> where T: Sync {}
|
||||
|
||||
impl<T> Deref for MutexGuard<'_, T> {
|
||||
type Target = T;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
unsafe { &*self.mutex.data.get() }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> DerefMut for MutexGuard<'_, T> {
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
unsafe { &mut *self.mutex.data.get() }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Mutex<T> {
|
||||
pub fn new(data: T) -> Mutex<T> {
|
||||
Mutex {
|
||||
cap: syscall::mutex_create().unwrap(),
|
||||
data: UnsafeCell::new(data),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn lock(&self) -> MutexGuard<T> {
|
||||
syscall::mutex_lock(&self.cap).unwrap();
|
||||
|
||||
MutexGuard { mutex: self }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Drop for MutexGuard<'_, T> {
|
||||
fn drop(&mut self) {
|
||||
syscall::mutex_release(&self.mutex.cap).unwrap();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue