Skip to content

Commit a44b836

Browse files
author
Markus Westerlind
committed
fix: Drop the value in the ThreadLocal on drop
Regressed in (1.1.1) fc5bfba
1 parent 322cf34 commit a44b836

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

src/lib.rs

+27
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,16 @@ struct Entry<T> {
119119
value: UnsafeCell<MaybeUninit<T>>,
120120
}
121121

122+
impl<T> Drop for Entry<T> {
123+
fn drop(&mut self) {
124+
unsafe {
125+
if *self.present.get_mut() {
126+
ptr::drop_in_place((*self.value.get()).as_mut_ptr());
127+
}
128+
}
129+
}
130+
}
131+
122132
// ThreadLocal is always Sync, even if T isn't
123133
unsafe impl<T: Send> Sync for ThreadLocal<T> {}
124134

@@ -602,6 +612,23 @@ mod tests {
602612
assert_eq!(vec![1, 2, 3], v);
603613
}
604614

615+
#[test]
616+
fn test_drop() {
617+
let local = ThreadLocal::new();
618+
struct Dropped(Arc<AtomicUsize>);
619+
impl Drop for Dropped {
620+
fn drop(&mut self) {
621+
self.0.fetch_add(1, Relaxed);
622+
}
623+
}
624+
625+
let dropped = Arc::new(AtomicUsize::new(0));
626+
local.get_or(|| Dropped(dropped.clone()));
627+
assert_eq!(dropped.load(Relaxed), 0);
628+
drop(local);
629+
assert_eq!(dropped.load(Relaxed), 1);
630+
}
631+
605632
#[test]
606633
fn is_sync() {
607634
fn foo<T: Sync>() {}

0 commit comments

Comments
 (0)