Crate atomic_ref [] [src]

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>.

To store an atomic reference in a static variable, a the macro static_atomic_ref! must be used. A static initializer like ATOMIC_REF_INIT is not possible due to the need to be generic over any reference target type.

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.

Examples

Static logger state

#[macro_use]
extern crate atomic_ref;
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 (Logger + Sync)
}

// The methods for working with our currently defined static logger
static_atomic_ref! {
    static LOGGER: AtomicRef<LoggerInfo>;
}
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);
}

Macros

static_atomic_ref

A macro to define a statically allocated AtomicRef<'static, T> which is initialized to None.

Structs

AtomicRef

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

Constants

ATOMIC_U8_REF_INIT

You will probably never need to use this type. It exists mostly for internal use in the static_atomic_ref! macro.