This commit is contained in:
Bryan McShea
2024-02-06 17:11:39 -05:00
parent f9e7f85a8c
commit 4cf2f5b29e
3 changed files with 50 additions and 0 deletions

View File

@@ -1 +1,3 @@
pub mod bits; pub mod bits;
pub mod mutex;
pub mod spin;

29
kernel/src/util/mutex.rs Normal file
View File

@@ -0,0 +1,29 @@
use super::spin::SpinLock;
struct Mutex<T> {
lock: SpinLock,
val: T,
}
impl<T> Mutex<T> {
pub fn new(val: T) -> Self {
Self {
lock: SpinLock::new(),
val,
}
}
pub fn lock(&mut self) -> MutexGuard<T> {
self.lock.lock();
MutexGuard { mutex: self }
}
}
struct MutexGuard<'a, T> {
mutex: &'a mut Mutex<T>,
}
impl <'a, T> Drop for MutexGuard<'a, T> {
fn drop(&mut self) {
self.mutex.lock.unlock();
}
}

19
kernel/src/util/spin.rs Normal file
View File

@@ -0,0 +1,19 @@
use core::sync::atomic::{AtomicBool, Ordering};
pub struct SpinLock {
pub locked: AtomicBool,
}
impl SpinLock {
pub fn new() -> Self {
Self {
locked: AtomicBool::new(false),
}
}
pub fn lock(&mut self) {
while self.locked.swap(true, Ordering::Acquire) {}
}
pub fn unlock(&mut self) {
self.locked.store(false, Ordering::Release)
}
}