From c2ec772dac7cf2a488af539613bf31ed15dfbaa5 Mon Sep 17 00:00:00 2001 From: Botahamec Date: Thu, 27 Oct 2022 17:35:32 -0400 Subject: Created a dumb `Lock` type --- src/lib.rs | 2 ++ src/lock.rs | 24 ++++++++++++++++++++++++ 2 files changed, 26 insertions(+) create mode 100644 src/lock.rs (limited to 'src') diff --git a/src/lib.rs b/src/lib.rs index 0922f35..53fc59a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -3,6 +3,8 @@ use std::fmt::{self, Debug}; use parking_lot::Mutex; +mod lock; + thread_local! { // safety: this is the only place where a ThreadLock is created pub static KEY: Mutex> = Mutex::new(Some(unsafe { ThreadKey::new() })); diff --git a/src/lock.rs b/src/lock.rs new file mode 100644 index 0000000..becdfaa --- /dev/null +++ b/src/lock.rs @@ -0,0 +1,24 @@ +use std::sync::atomic::{AtomicBool, Ordering}; + +#[derive(Debug, Default)] +pub struct Lock { + is_locked: AtomicBool, +} + +impl Lock { + pub const fn new() -> Self { + Self { + is_locked: AtomicBool::new(false), + } + } + + pub fn try_lock(&self) -> bool { + self.is_locked + .compare_exchange_weak(false, true, Ordering::Acquire, Ordering::Relaxed) + .is_ok() + } + + pub fn unlock(&self) { + self.is_locked.store(false, Ordering::Release) + } +} -- cgit v1.2.3