Concurrency Safety · 19 min · free lesson

Atomic State

Update one shared value without a lock.

Core idea

Atomic operations are indivisible but still need an ordering that describes cross-thread visibility.

Diagram for Atomic State: a Rust code example flows to the lesson rule and the key observation.
fetch_add updates the count as one indivisible step; Relaxed orders no other memory.

Understand it

Atomic operations are indivisible but still need an ordering that describes cross-thread visibility. Use the weakest ordering justified by a written synchronization argument, not by habit.

An atomic value supports operations that are indivisible with respect to competing threads. fetch_add on AtomicUsize, for example, prevents two workers from losing an increment by reading and writing the same stale count. This makes atomics a good fit for simple counters, flags, and some carefully designed state machines. It does not turn a sequence of several atomic operations into one transaction. If two fields must change together, a mutex may express the invariant more clearly.

Memory ordering answers a second question: when another thread sees an atomic change, which ordinary memory writes are guaranteed visible too? Relaxed is enough for a count whose only requirement is an accurate final total after workers join. A flag that publishes prepared data generally needs a release store and an acquire load, or another synchronization design. SeqCst gives a stronger global ordering model, but choosing it blindly does not fix a flawed state machine.

Start with several threads incrementing a shared atomic counter and compare fetch_add with a failed idea built from separate load and store calls. Then draw a producer that fills a buffer and sets a ready flag; explain why the consumer must not read the buffer before it observes readiness through an appropriate synchronization operation. Keep unsafe shared-memory examples out of an introductory exercise. State the invariant first, pick the weakest ordering you can justify only after understanding it, and prefer a mutex if the proof is hard to explain.

Read the code

use std::sync::atomic::{
    AtomicUsize, Ordering,
};
let count = AtomicUsize::new(0);
count.fetch_add(1, Ordering::Relaxed);

fetch_add updates the count as one indivisible step; Relaxed orders no other memory.

Practice starter

use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::thread;

let data = AtomicUsize::new(0);
let ready = AtomicBool::new(false);
thread::scope(|scope| {
    scope.spawn(|| {
        data.store(42, Ordering::Relaxed);
        ready.store(true, Ordering::Release);
    });
    scope.spawn(|| {
        while !ready.load(Ordering::Acquire) {
            std::hint::spin_loop();
        }
        println!("{}", data.load(Ordering::Relaxed));
    });
});

Practise this code in Playground ↗

Try it

Predict what the second thread prints, and name the Release store and the Acquire load that make the answer certain.

What success looks like: You can say why Relaxed is enough for a count and why this ready flag needs more.

Check your understanding

What does an atomic ordering describe?

Reveal the answer
  1. What other memory effects become visible
  2. The size of the integer
  3. How many threads may run

An ordering says which other memory effects become visible with an atomic change. Here, the Acquire load that sees true is also guaranteed to see the store of 42.

Go deeper

Common misconception: “An atomic operation makes every nearby memory access safe to read from another thread.”

An atomic operation is indivisible only for that one value. Its ordering states what else another thread may see, so publishing data takes a Release store and an Acquire load.

  1. Create the atomic: AtomicUsize::new(0) needs no mut: updates go through a shared reference, which is what lets threads share it.
  2. Apply fetch_add: fetch_add(1, Ordering::Relaxed) reads, adds, and writes as one step, and returns the previous value, 0 here.
  3. Check the ordering: Relaxed keeps this single update atomic but orders no other memory, so it cannot publish data to another thread.

Transfer challenge: Spawn four scoped threads that each add 1,000 to count, first with fetch_add and then with separate load and store. Predict each total and explain any lost updates.

Connections

  • Mutex Poisoning: Notice a panic that may leave state inconsistent
  • Deadlock Avoidance: Keep a global lock order and short critical sections
Learn this lesson with AI

Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.

I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools.
Lesson: Atomic State (courseId "concurrency", lessonId "atomics-basics")
Link: https://crabrix.com/learn/concurrency/atomics-basics/
Goal: Atomic operations are indivisible but still need an ordering that describes cross-thread visibility.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=concurrency/atomics-basics) and I will write the code there.
Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.