Crate atomic_ref[][src]

Expand description

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.


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.


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) {
    } else {
fn set_logger(logger: Option<&'static LoggerInfo>) {, Ordering::SeqCst);

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

fn main() {
    let res = log("This will fail");
    let res = log("This will succeed");


A mutable Option<&'a T> type which can be safely shared between threads.