Skip to content
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 9 additions & 15 deletions packages/kernel/src/sync/mutex.rs
Original file line number Diff line number Diff line change
@@ -1,23 +1,23 @@
use core::sync::atomic::{AtomicU8, Ordering};
use std::cell::UnsafeCell;
use critical_section::RestoreState;

pub use lock_api::MutexGuard;
pub type Mutex<T> = lock_api::Mutex<RawMutex, T>;

struct MutexState(AtomicU8);
struct MutexState(UnsafeCell<RestoreState>);
impl MutexState {
const fn new() -> Self {
Self(AtomicU8::new(0))
Self(UnsafeCell::new(RestoreState::invalid()))
}

/// Returns true if the lock was acquired.
fn try_lock(&self) -> bool {
self.0
.compare_exchange(0, 1, Ordering::Acquire, Ordering::Acquire)
.is_ok()
unsafe { *self.0.get() = critical_section::acquire() }
true
}

fn unlock(&self) {
self.0.store(0, Ordering::Release);
unsafe { critical_section::release(self.0.into_inner()) }
}
}

Expand All @@ -42,20 +42,14 @@ unsafe impl lock_api::RawMutex for RawMutex {
type GuardMarker = lock_api::GuardSend;

fn lock(&self) {
critical_section::with(|_| {
while !self.state.try_lock() {
core::hint::spin_loop();
}
})
critical_section::with(|_| self.state.try_lock())
}

fn try_lock(&self) -> bool {
critical_section::with(|_| self.state.try_lock())
}

unsafe fn unlock(&self) {
critical_section::with(|_| {
self.state.unlock();
})
critical_section::with(|_| self.state.unlock())
}
}