Skip to content

Commit

Permalink
Fix rust-random#911: use Once instead of AtomicBool
Browse files Browse the repository at this point in the history
  • Loading branch information
dhardy committed Jan 8, 2020
1 parent a67173e commit ae3a416
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 9 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -12,6 +12,7 @@ You may also find the [Upgrade Guide](https://rust-random.github.io/book/update.
### Fixes
- The `Bernoulli` distribution constructors now reports an error on NaN and on
`denominator == 0`. (#925)
- Use `std::sync::Once` to register fork handler, avoiding possible atomicity violation (#928)

### Changes
- Unix: make libc dependency optional; only use fork protection with std feature (#928)
Expand Down
16 changes: 7 additions & 9 deletions src/rngs/adapter/reseeding.rs
Expand Up @@ -281,9 +281,10 @@ where

#[cfg(all(unix, feature = "std", not(target_os = "emscripten")))]
mod fork {
use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use core::sync::atomic::{AtomicUsize, Ordering};
#[allow(deprecated)] // Required for compatibility with Rust < 1.24.
use core::sync::atomic::{ATOMIC_BOOL_INIT, ATOMIC_USIZE_INIT};
use core::sync::atomic::{ATOMIC_USIZE_INIT};
use std::sync::Once;

// Fork protection
//
Expand All @@ -304,20 +305,17 @@ mod fork {
RESEEDING_RNG_FORK_COUNTER.load(Ordering::Relaxed)
}

#[allow(deprecated)]
static FORK_HANDLER_REGISTERED: AtomicBool = ATOMIC_BOOL_INIT;

extern "C" fn fork_handler() {
// Note: fetch_add is defined to wrap on overflow
// (which is what we want).
RESEEDING_RNG_FORK_COUNTER.fetch_add(1, Ordering::Relaxed);
}

pub fn register_fork_handler() {
if !FORK_HANDLER_REGISTERED.load(Ordering::Relaxed) {
unsafe { libc::pthread_atfork(None, None, Some(fork_handler)) };
FORK_HANDLER_REGISTERED.store(true, Ordering::Relaxed);
}
static REGISTER: Once = Once::new();
REGISTER.call_once(|| unsafe {
libc::pthread_atfork(None, None, Some(fork_handler));
});
}
}

Expand Down

1 comment on commit ae3a416

@BurtonQin
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good fix!

Please sign in to comment.