work
This commit is contained in:
@@ -1 +1,3 @@
|
|||||||
pub mod bits;
|
pub mod bits;
|
||||||
|
pub mod mutex;
|
||||||
|
pub mod spin;
|
||||||
|
|||||||
29
kernel/src/util/mutex.rs
Normal file
29
kernel/src/util/mutex.rs
Normal 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
19
kernel/src/util/spin.rs
Normal 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)
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user