Skip to content

Commit

Permalink
fix: Drop the value in the ThreadLocal on drop
Browse files Browse the repository at this point in the history
Regressed in (1.1.1) fc5bfba
  • Loading branch information
Markus Westerlind committed Feb 4, 2021
1 parent 322cf34 commit a44b836
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,16 @@ struct Entry<T> {
value: UnsafeCell<MaybeUninit<T>>,
}

impl<T> Drop for Entry<T> {
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<T: Send> Sync for ThreadLocal<T> {}

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

#[test]
fn test_drop() {
let local = ThreadLocal::new();
struct Dropped(Arc<AtomicUsize>);
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<T: Sync>() {}
Expand Down

0 comments on commit a44b836

Please sign in to comment.