Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Standard Library Modules

The std::sync::atomic module

Reference for std::sync::atomic: AtomicUsize, AtomicBool and friends, load, store, fetch_add, compare_exchange, fetch_update and the memory Ordering values.

std::sync::atomic offers integer, boolean and pointer types whose operations happen as one indivisible step, even when several threads use them at once, without a lock. The types are AtomicBool, AtomicI8 to AtomicI64, AtomicU8 to AtomicU64, AtomicIsize, AtomicUsize and AtomicPtr<T>. They are the building blocks for counters, flags, and lock-free data structures.

Every operation takes an Ordering that says how much the operation may be reordered relative to other memory accesses. Relaxed guarantees only atomicity of that one variable. Acquire/Release pair up to publish data from one thread to another. SeqCst is the strongest, giving all threads one agreed order.

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

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

Try it

Rust A shared 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 compare_exchange, swap 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

Method Description
new(v) const fn, so atomics can be static.
load(order), store(v, order) Read or write. load accepts Relaxed, Acquire, SeqCst; store accepts Relaxed, Release, SeqCst.
swap(v, order) Store and return the old value.
compare_exchange(current, new, success, failure) Result<T, T>: Ok(old) if it matched, else Err(actual).
compare_exchange_weak(...) May fail spuriously; faster in retry loops.
fetch_add, fetch_sub, fetch_and, fetch_or, fetch_xor, fetch_nand, fetch_max, fetch_min Update and return the previous value. Arithmetic wraps.
try_update(set_order, fetch_order, f) Result<T, T>; loops with compare_exchange_weak until f returns Some. Its old name fetch_update is deprecated on current compilers (Rust 1.99) and produces a warning.
get_mut(), into_inner() Plain access when you hold &mut self or own the atomic.
fence(order), compiler_fence(order) Standalone memory barriers.
Ordering Meaning
Relaxed Atomic, no ordering with other variables. Fine for statistics counters.
Acquire On loads: later reads/writes cannot move before it.
Release On stores: earlier reads/writes cannot move after it.
AcqRel Both, for read-modify-write operations.
SeqCst Acquire/release plus a single global order of all SeqCst operations.

Errors and edge cases: load(Ordering::Release) or store(_, Ordering::Acquire) panics at run time. The failure ordering of compare_exchange cannot be stronger than the success ordering and cannot be Release or AcqRel.

Usage notes

  • Pair a Release store with an Acquire load to publish data: everything the writer did before the store is visible to the reader after the load sees the value.
  • When unsure, use SeqCst; it is the easiest to reason about. Weaker orderings are an optimization that needs proof.
  • Atomics make one variable safe; a multi-field invariant still needs a Mutex.
  • Compare-and-swap loops must handle the ABA problem when used for pointers.
  • Not every width exists on every target: AtomicU64 is missing on some 32-bit platforms (check cfg(target_has_atomic)).
  • A spin loop on a flag wastes CPU; use thread::yield_now, park or a Condvar if the wait can be long.
  • AtomicBool::fetch_not, AtomicPtr and the Atomic* from_ptr methods exist for lower-level code.