From 0b49b056981f4c5bcbdbb7fada1a8379e0793c86 Mon Sep 17 00:00:00 2001 From: Botahamec Date: Fri, 28 Oct 2022 22:20:05 -0400 Subject: Implemented SpinLock --- src/mutex.rs | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) (limited to 'src/mutex.rs') 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. /// -- cgit v1.2.3