From 4cf2f5b29e88b1888c880c10d537da6ae491ae00 Mon Sep 17 00:00:00 2001 From: Bryan McShea Date: Tue, 6 Feb 2024 17:11:39 -0500 Subject: [PATCH] work --- kernel/src/util/mod.rs | 2 ++ kernel/src/util/mutex.rs | 29 +++++++++++++++++++++++++++++ kernel/src/util/spin.rs | 19 +++++++++++++++++++ 3 files changed, 50 insertions(+) create mode 100644 kernel/src/util/mutex.rs create mode 100644 kernel/src/util/spin.rs diff --git a/kernel/src/util/mod.rs b/kernel/src/util/mod.rs index e79b623..c3594e1 100644 --- a/kernel/src/util/mod.rs +++ b/kernel/src/util/mod.rs @@ -1 +1,3 @@ pub mod bits; +pub mod mutex; +pub mod spin; diff --git a/kernel/src/util/mutex.rs b/kernel/src/util/mutex.rs new file mode 100644 index 0000000..f2e2e7d --- /dev/null +++ b/kernel/src/util/mutex.rs @@ -0,0 +1,29 @@ +use super::spin::SpinLock; + +struct Mutex { + lock: SpinLock, + val: T, +} + +impl Mutex { + pub fn new(val: T) -> Self { + Self { + lock: SpinLock::new(), + val, + } + } + pub fn lock(&mut self) -> MutexGuard { + self.lock.lock(); + MutexGuard { mutex: self } + } +} + +struct MutexGuard<'a, T> { + mutex: &'a mut Mutex, +} + +impl <'a, T> Drop for MutexGuard<'a, T> { + fn drop(&mut self) { + self.mutex.lock.unlock(); + } +} diff --git a/kernel/src/util/spin.rs b/kernel/src/util/spin.rs new file mode 100644 index 0000000..1fbedd7 --- /dev/null +++ b/kernel/src/util/spin.rs @@ -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) + } +}