garbage self made raw spin lock 😎
This commit is contained in:
@@ -1,29 +1,44 @@
|
||||
use core::ops::{Deref, DerefMut};
|
||||
|
||||
use super::spin::SpinLock;
|
||||
|
||||
struct Mutex<T> {
|
||||
pub struct Mutex<T> {
|
||||
lock: SpinLock,
|
||||
val: T,
|
||||
}
|
||||
|
||||
impl<T> Mutex<T> {
|
||||
pub fn new(val: T) -> Self {
|
||||
pub const fn new(val: T) -> Self {
|
||||
Self {
|
||||
lock: SpinLock::new(),
|
||||
val,
|
||||
}
|
||||
}
|
||||
pub fn lock(&mut self) -> MutexGuard<T> {
|
||||
pub fn lock(&self) -> MutexGuard<T> {
|
||||
self.lock.lock();
|
||||
MutexGuard { mutex: self }
|
||||
}
|
||||
}
|
||||
|
||||
struct MutexGuard<'a, T> {
|
||||
mutex: &'a mut Mutex<T>,
|
||||
pub struct MutexGuard<'a, T> {
|
||||
mutex: &'a Mutex<T>,
|
||||
}
|
||||
|
||||
impl <'a, T> Drop for MutexGuard<'a, T> {
|
||||
impl<'a, T> Drop for MutexGuard<'a, T> {
|
||||
fn drop(&mut self) {
|
||||
self.mutex.lock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T> Deref for MutexGuard<'a, T> {
|
||||
type Target = T;
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.mutex.val
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T> DerefMut for MutexGuard<'a, T> {
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
unsafe {&mut (*(self.mutex as *const Mutex<T> as *mut Mutex<T>)).val}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,15 +5,15 @@ pub struct SpinLock {
|
||||
}
|
||||
|
||||
impl SpinLock {
|
||||
pub fn new() -> Self {
|
||||
pub const fn new() -> Self {
|
||||
Self {
|
||||
locked: AtomicBool::new(false),
|
||||
}
|
||||
}
|
||||
pub fn lock(&mut self) {
|
||||
pub fn lock(&self) {
|
||||
while self.locked.swap(true, Ordering::Acquire) {}
|
||||
}
|
||||
pub fn unlock(&mut self) {
|
||||
pub fn unlock(&self) {
|
||||
self.locked.store(false, Ordering::Release)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user