Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Relax atomic orderings #520

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
29 changes: 13 additions & 16 deletions src/lib.rs
Expand Up @@ -406,7 +406,7 @@ const UNINITIALIZED: usize = 0;
const INITIALIZING: usize = 1;
const INITIALIZED: usize = 2;

static MAX_LOG_LEVEL_FILTER: AtomicUsize = AtomicUsize::new(0);
static MAX_LOG_LEVEL_FILTER: AtomicUsize = AtomicUsize::new(LevelFilter::Off as usize);

static LOG_LEVEL_NAMES: [&str; 6] = ["OFF", "ERROR", "WARN", "INFO", "DEBUG", "TRACE"];

Expand Down Expand Up @@ -1346,24 +1346,21 @@ fn set_logger_inner<F>(make_logger: F) -> Result<(), SetLoggerError>
where
F: FnOnce() -> &'static dyn Log,
{
let old_state = match STATE.compare_exchange(
match STATE.compare_exchange(
UNINITIALIZED,
INITIALIZING,
Ordering::SeqCst,
Ordering::SeqCst,
Ordering::Acquire,
Ordering::Relaxed,
) {
Ok(s) | Err(s) => s,
};
match old_state {
UNINITIALIZED => {
Ok(UNINITIALIZED) => {
unsafe {
LOGGER = make_logger();
}
STATE.store(INITIALIZED, Ordering::SeqCst);
STATE.store(INITIALIZED, Ordering::Release);
Ok(())
}
INITIALIZING => {
while STATE.load(Ordering::SeqCst) == INITIALIZING {
Err(INITIALIZING) => {
while STATE.load(Ordering::Relaxed) == INITIALIZING {
// TODO: replace with `hint::spin_loop` once MSRV is 1.49.0.
#[allow(deprecated)]
std::sync::atomic::spin_loop_hint();
Expand Down Expand Up @@ -1394,10 +1391,10 @@ where
///
/// [`set_logger`]: fn.set_logger.html
pub unsafe fn set_logger_racy(logger: &'static dyn Log) -> Result<(), SetLoggerError> {
match STATE.load(Ordering::SeqCst) {
match STATE.load(Ordering::Acquire) {
UNINITIALIZED => {
LOGGER = logger;
STATE.store(INITIALIZED, Ordering::SeqCst);
STATE.store(INITIALIZED, Ordering::Release);
Ok(())
}
INITIALIZING => {
Expand Down Expand Up @@ -1446,11 +1443,11 @@ impl error::Error for ParseLevelError {}
///
/// If a logger has not been set, a no-op implementation is returned.
pub fn logger() -> &'static dyn Log {
if STATE.load(Ordering::SeqCst) != INITIALIZED {
if STATE.load(Ordering::Acquire) == INITIALIZED {
unsafe { LOGGER }
} else {
static NOP: NopLogger = NopLogger;
&NOP
} else {
unsafe { LOGGER }
}
}

Expand Down