Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Standard Library Modules

Rust atomic types

Reference for std::sync::atomic types: load, store, swap, compare_exchange, fetch_add, try_update, memory orderings, wrapping behavior and lock-free counters and flags.

The std::sync::atomic module has types such as AtomicBool, AtomicUsize, AtomicI32, AtomicU64 and AtomicPtr<T>. Each wraps one value and lets several threads read and modify it without a lock, using single indivisible hardware operations. Every operation takes a memory Ordering that states how much it synchronizes with other threads.

All the methods take &self, so an atomic can live in a static or be shared by reference or Arc, and it needs no mut. Atomics are the right tool for counters, flags, ids and statistics. For anything that touches more than one value, use a Mutex.

Rust
use std::sync::atomic::{AtomicUsize, Ordering};

static HITS: AtomicUsize = AtomicUsize::new(0);
HITS.fetch_add(1, Ordering::Relaxed);

Try it

Rust A counter and a stop flag

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust swap, compare_exchange and try_update

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

Rust
impl AtomicUsize {   // the same shape for AtomicI8..AtomicU64, AtomicIsize
    pub const fn new(v: usize) -> AtomicUsize;
    pub fn load(&self, order: Ordering) -> usize;
    pub fn store(&self, val: usize, order: Ordering);
    pub fn swap(&self, val: usize, order: Ordering) -> usize;
    pub fn compare_exchange(&self, current: usize, new: usize, success: Ordering, failure: Ordering)
        -> Result<usize, usize>;
    pub fn compare_exchange_weak(/* same */) -> Result<usize, usize>;
    pub fn fetch_add(&self, val: usize, order: Ordering) -> usize;   // also fetch_sub
    pub fn fetch_and(&self, val: usize, order: Ordering) -> usize;   // also fetch_or, fetch_xor, fetch_nand
    pub fn fetch_max(&self, val: usize, order: Ordering) -> usize;   // also fetch_min
    pub fn try_update<F>(&self, set: Ordering, fetch: Ordering, f: F) -> Result<usize, usize>
    where F: FnMut(usize) -> Option<usize>;
    pub fn update<F>(&self, set: Ordering, fetch: Ordering, f: F) -> usize
    where F: FnMut(usize) -> usize;
    pub fn get_mut(&mut self) -> &mut usize;
    pub fn into_inner(self) -> usize;
}

AtomicBool has fetch_and, fetch_or, fetch_xor, fetch_not and fetch_nand but no fetch_add. AtomicPtr<T> has load, store, swap and compare_exchange on *mut T.

Name Description
order A memory Ordering: Relaxed, Acquire, Release, AcqRel or SeqCst.
current, new compare_exchange stores new only if the value equals current.
success, failure Orderings for the two outcomes; failure cannot be Release or AcqRel and cannot be stronger than success.

Returns. All fetch_* methods and swap return the value from before the change. compare_exchange returns Ok(previous) on success and Err(actual) on failure.

Errors and panics. load panics with Release or AcqRel; store panics with Acquire or AcqRel. fetch_add and fetch_sub wrap around on overflow, never panic.

Usage notes

  • Relaxed for independent counters. If nothing else depends on the value, Relaxed is enough and the cheapest. Use Release on the store and Acquire on the load to publish other data; use SeqCst when unsure.
  • compare_exchange_weak may fail spuriously but is faster in loops on some CPUs. Use compare_exchange when not looping.
  • try_update was fetch_update. The old name still works but is deprecated on current compilers. try_update retries your closure until the compare-exchange wins or the closure returns None; update is the version whose closure always returns a value.
  • Atomics are not a lock. Two separate atomics can be read in an inconsistent state. If two fields must change together, put them in a Mutex.
  • Spin loops burn CPU. Use std::hint::spin_loop() for tiny waits, otherwise thread::park, a Condvar or a channel.
  • ABA problem. A compare-exchange only checks the value, not whether it changed and changed back. Be careful building lock-free structures; prefer proven crates.
  • Availability. AtomicU64 and AtomicI64 exist only on targets with 64-bit atomics (#[cfg(target_has_atomic = "64")]). AtomicBool and AtomicUsize exist everywhere that has atomics.
  • Layout. Atomic* has the same size and alignment as its integer, and from_mut is available on some types to view a &mut as atomic.
  • Cache contention. Many threads hammering one atomic still slow each other down. Give each thread its own counter and add them at the end.