diff options
| author | Botahamec <botahamec@outlook.com> | 2022-10-28 22:20:05 -0400 |
|---|---|---|
| committer | Botahamec <botahamec@outlook.com> | 2022-10-28 22:20:05 -0400 |
| commit | 0b49b056981f4c5bcbdbb7fada1a8379e0793c86 (patch) | |
| tree | f0f03db59a7286a421aafad31c062ed1edd64885 /src/mutex.rs | |
| parent | d00df37bc92fccaa39e69bf886f9c8cd5522817b (diff) | |
Implemented SpinLock
Diffstat (limited to 'src/mutex.rs')
| -rw-r--r-- | src/mutex.rs | 33 |
1 files changed, 33 insertions, 0 deletions
diff --git a/src/mutex.rs b/src/mutex.rs index a152eda..6c2e254 100644 --- a/src/mutex.rs +++ b/src/mutex.rs @@ -1,6 +1,7 @@ use std::cell::UnsafeCell; use std::ops::{Deref, DerefMut}; +use crate::lock::Lock; use crate::ThreadKey; /// Implements a raw C-like mutex. @@ -31,6 +32,38 @@ pub unsafe trait RawMutex { unsafe fn unlock(&self); } +/// A raw mutex which just spins +pub struct RawSpin { + lock: Lock, +} + +unsafe impl RawMutex for RawSpin { + const INIT: Self = Self { lock: Lock::new() }; + + fn lock(&self) { + loop { + std::hint::spin_loop(); + + if let Some(key) = self.lock.try_lock() { + std::mem::forget(key); + return; + } + } + } + + fn try_lock(&self) -> bool { + self.lock.try_lock().is_some() + } + + fn is_locked(&self) -> bool { + self.lock.is_locked() + } + + unsafe fn unlock(&self) { + self.lock.force_unlock(); + } +} + /// A mutual exclusion primitive useful for protecting shared data, which /// cannot deadlock. /// |
