From a44b836f90e0317d256ed1dd4cff745feff285ea Mon Sep 17 00:00:00 2001 From: Markus Westerlind Date: Thu, 4 Feb 2021 16:30:47 +0100 Subject: [PATCH] fix: Drop the value in the ThreadLocal on drop Regressed in (1.1.1) https://github.com/Amanieu/thread_local-rs/commit/fc5bfba36ed1f0aac527eb0a814fec104adc69ed --- src/lib.rs | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index 98387ed..f26f6ed 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -119,6 +119,16 @@ struct Entry { value: UnsafeCell>, } +impl Drop for Entry { + fn drop(&mut self) { + unsafe { + if *self.present.get_mut() { + ptr::drop_in_place((*self.value.get()).as_mut_ptr()); + } + } + } +} + // ThreadLocal is always Sync, even if T isn't unsafe impl Sync for ThreadLocal {} @@ -602,6 +612,23 @@ mod tests { assert_eq!(vec![1, 2, 3], v); } + #[test] + fn test_drop() { + let local = ThreadLocal::new(); + struct Dropped(Arc); + impl Drop for Dropped { + fn drop(&mut self) { + self.0.fetch_add(1, Relaxed); + } + } + + let dropped = Arc::new(AtomicUsize::new(0)); + local.get_or(|| Dropped(dropped.clone())); + assert_eq!(dropped.load(Relaxed), 0); + drop(local); + assert_eq!(dropped.load(Relaxed), 1); + } + #[test] fn is_sync() { fn foo() {}