Crate atom_box

source ·
Expand description

Atom Box

This crate provides a safe idiomatic Rust API for an Atomic Box with safe memory reclamation when used in multi-threaded concurrent lock-free data structures.

Under the covers it uses Hazard Pointers to ensure memory is only reclaimed when all references are dropped.

The main type provided is the AtomBox.

Examples

use atom_box::AtomBox;
use std::{sync::Arc, thread};

const ITERATIONS: usize = 1000;

let atom_box1 = Arc::new(AtomBox::new(0));
let atom_box2 = Arc::new(AtomBox::new(0));

let a_box1 = atom_box1.clone();
let handle1 = thread::spawn(move || {
    let mut current_value = 0;
    for _ in 1..=ITERATIONS {
        let new_value = a_box1.load();
        assert!(*new_value >= current_value, "Value should not decrease");
        current_value = *new_value;
    }
});

let a_box1 = atom_box1.clone();
let a_box2 = atom_box2.clone();
let handle2 = thread::spawn(move || {
    for i in 1..=ITERATIONS {
        let guard1 = a_box1.swap(i);
        let value1 = *guard1;
        let guard2 = a_box2.swap_from_guard(guard1);
        assert!(
            *guard2 <= value1,
            "Value in first box should be greater than or equal to value in second box"
        );
    }
});

handle1.join().unwrap();
handle2.join().unwrap();

Modules

Structs

  • A box which can safely be shared between threads and atomically updated.
  • Contains a reference to a value that was stored in a AtomBox.
  • Contains a reference to a value that was previously contained in an AtomBox.