From 7f73e25dfb47f860b9bbd0ad594b9a6695b8c597 Mon Sep 17 00:00:00 2001 From: Botahamec Date: Wed, 26 Oct 2022 22:29:16 -0400 Subject: Created ThreadKey --- src/lib.rs | 36 ++++++++++++++++++++++++++---------- 1 file changed, 26 insertions(+), 10 deletions(-) (limited to 'src') diff --git a/src/lib.rs b/src/lib.rs index 7d12d9a..3e18d9f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,14 +1,30 @@ -pub fn add(left: usize, right: usize) -> usize { - left + right +use parking_lot::Mutex; + +thread_local! { + // safety: this is the only place where a ThreadLock is created + pub static KEY: Mutex> = Mutex::new(Some(unsafe { ThreadKey::new() })); +} + +#[derive(Debug, PartialEq, Eq, Hash)] +pub struct ThreadKey { + _priv: *const (), // this isn't Send or Sync } -#[cfg(test)] -mod tests { - use super::*; +impl ThreadKey { + unsafe fn new() -> Self { + Self { + _priv: std::ptr::null(), + } + } + + pub fn lock() -> Option { + KEY.with(|thread_lock| thread_lock.lock().take()) + } - #[test] - fn it_works() { - let result = add(2, 2); - assert_eq!(result, 4); - } + pub fn unlock(lock: ThreadKey) { + KEY.with(|thread_lock| { + let mut thread_lock = thread_lock.lock(); + *thread_lock = Some(lock); + }) + } } -- cgit v1.2.3