Skip to content

Commit

Permalink
Merge pull request #30 from Marwes/fix_drop
Browse files Browse the repository at this point in the history
fix: Drop the value in the ThreadLocal on drop
  • Loading branch information
Amanieu authored Feb 4, 2021
2 parents 322cf34 + a44b836 commit 5e8bbf2
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 5e8bbf2

Please sign in to comment.