Atomics

RecipeCratesCategories
Standard Atomic Typesstdcat-concurrency
arc-swaparc-swapcat-concurrency

Standard Atomic Types

std crossbeam cat-concurrency

Atomic types in std::sync::atomic⮳ provide primitive shared-memory communication between threads, and are the building blocks of other concurrent types. It defines atomic versions of a select number of primitive types, including std::sync::atomic::AtomicBool⮳, std::sync::atomic::AtomicIsize⮳, std::sync::atomic::AtomicUsize⮳, std::sync::atomic::AtomicI8⮳, std::sync::atomic::AtomicU16⮳, etc.

use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;

// Declare a static atomic counter to track the number of live threads.
static GLOBAL_THREAD_COUNT: AtomicUsize = AtomicUsize::new(0);

fn main() {
    let old_thread_count = GLOBAL_THREAD_COUNT.fetch_add(1, Ordering::SeqCst);
    println!("Live threads: {}", old_thread_count + 1);
}

The most common way to share an atomic variable is to put it into an std::sync::Arc⮳ (an atomically-reference-counted shared pointer).

crossbeam⮳ also offers crossbeam::atomic::AtomicCell⮳, a thread-safe mutable memory location. This type is equivalent to std::cell::Cell⮳, except it can also be shared among multiple threads.

use crossbeam_utils::atomic::AtomicCell;

/// Demonstrates the use of `AtomicCell` from the `crossbeam-utils` crate.
fn main() {
    // Create a new AtomicCell with an initial value of 7.
    let a = AtomicCell::new(7);

    // Extract the inner value from the AtomicCell.
    let v = a.into_inner();
    assert_eq!(v, 7);
    println!("{}", v);
}

Atomic Operations

std::sync::atomic provides atomic types for safe concurrent access to data. Essential for multi-threaded programming.

arc-swap

arc-swap arc-swap-crates.io arc-swap-github arc-swap-lib.rs cat-data-structures cat-memory-management

The ArcSwap type in arc-swap is a container for an Arc that can be changed atomically. Semantically, it is similar to Atomic<Arc<T>> (if there was such a thing) or RwLock<Arc<T>> (but without the need for the locking). It is optimized for read-mostly scenarios, with consistent performance characteristics.