#atomic #reference #static #order

atomic_ref

Atomic &'a T types with support for static allocation

4 releases

Uses old Rust 2015

0.2.1 Sep 19, 2021
0.2.0 Nov 1, 2020
0.1.2 Nov 4, 2016
0.1.1 Sep 3, 2016
0.1.0 Sep 2, 2016

#113 in #order

Download history 76/week @ 2024-07-22 170/week @ 2024-07-29 71/week @ 2024-08-05 129/week @ 2024-08-12 103/week @ 2024-08-19 101/week @ 2024-08-26 139/week @ 2024-09-02 52/week @ 2024-09-09 43/week @ 2024-09-16 130/week @ 2024-09-23 68/week @ 2024-09-30 64/week @ 2024-10-07 84/week @ 2024-10-14 80/week @ 2024-10-21 92/week @ 2024-10-28 38/week @ 2024-11-04

295 downloads per month
Used in 2 crates

MIT license

18KB
161 lines

AtomicRef

Build Status

An atomic optional reference with support for static allocation.

See the documentation for more information.


lib.rs:

Atomic References

These types act similarially to the Atomic types from std::sync::atomic, Except that instead of containing an integer type or a pointer, they contain an Option<&'a T> value.

Like other option values, these types present operations which, when used correctly, synchronize updates between threads. This type is a form of interior mutability, like Cell<T>, RefCell<T>, or Mutex<T>.

This type in static position is often used for lazy global initialization.

AtomicRef may only contain Sized types, as unsized types have wide pointers which cannot be atomically written to or read from.

Ordering

It is unsound to load or store an atomic reference with the Relaxed memory ordering, as these operations provide no ordering on writes to the data behind the reference. To avoid this issue, loads and stores with Relaxed memory ordering are actually performed with Acquire, Release, or AcqRel ordering, as appropriate.

Examples

Static logger state

use atomic_ref::AtomicRef;
use std::sync::atomic::Ordering;
use std::io::{stdout, Write};

// Define the idea of a logger
trait Logger {
    fn log(&self, msg: &str) {}
}
struct LoggerInfo {
    logger: &'static (dyn Logger + Sync)
}

// The methods for working with our currently defined static logger
static LOGGER: AtomicRef<LoggerInfo> = AtomicRef::new(None);
fn log(msg: &str) -> bool {
    if let Some(info) = LOGGER.load(Ordering::SeqCst) {
        info.logger.log(msg);
        true
    } else {
        false
    }
}
fn set_logger(logger: Option<&'static LoggerInfo>) {
    LOGGER.store(logger, Ordering::SeqCst);
}

// Defining the standard out example logger
struct StdoutLogger;
impl Logger for StdoutLogger {
    fn log(&self, msg: &str) {
        stdout().write(msg.as_bytes());
    }
}
static STDOUT_LOGGER: LoggerInfo = LoggerInfo { logger: &StdoutLogger };

fn main() {
    let res = log("This will fail");
    assert!(!res);
    set_logger(Some(&STDOUT_LOGGER));
    let res = log("This will succeed");
    assert!(res);
}

No runtime deps