From 7f73e25dfb47f860b9bbd0ad594b9a6695b8c597 Mon Sep 17 00:00:00 2001 From: Botahamec Date: Wed, 26 Oct 2022 22:29:16 -0400 Subject: Created ThreadKey --- Cargo.toml | 1 + src/lib.rs | 36 ++++++++++++++++++++++++++---------- 2 files changed, 27 insertions(+), 10 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index af1d8e3..91c85bf 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,3 +6,4 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] +parking_lot = "0.12" \ No newline at end of file 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