Memory Models & Atomics

the atomic types (_Atomic / std::atomic)

/ _Atomic -> uh-TOM-ik /

If an ordinary variable is a slip of paper anyone can scribble on at any time, an atomic type is the same value kept behind a special counter that only ever hands it out or takes it back as one clean transaction. It is how the three languages let you DECLARE that a particular location will be touched by several threads, so the compiler emits the right instructions and stops doing optimizations that would be wrong under concurrency.

In C11 you write _Atomic int x; (or use the atomic_int typedef from <stdatomic.h>). In C++ you write std::atomic<int> x;. In Rust you use the std::sync::atomic types such as AtomicU32 or AtomicUsize, accessed through methods like load() and store(). Operations on these types take a memory_order argument (defaulting to the strongest, seq_cst, in C++/C) that says how strongly this access is ordered against other memory. The compiler guarantees each load/store/read-modify-write is atomic and will not invent, duplicate, fuse, or hoist these accesses the way it freely does for plain variables.

Two honest cautions. First, an atomic type is not automatically lock-free: ask the runtime via atomic_is_lock_free() (C) or is_lock_free() (C++) — large structs may be implemented with a hidden mutex. Second, atomicity does not make the surrounding code correct: you still choose orderings deliberately, and wrapping every variable in std::atomic is usually slower and no more correct than a plain mutex around a critical section. Atomics are a sharp, low-level tool for building locks and lock-free structures, not a magic 'thread-safe variable'.

#include <stdatomic.h> atomic_bool ready = false; atomic_store(&ready, true); /* publishing thread */ while (!atomic_load(&ready)) { /* spin */ } /* consuming thread */

Declaring the flag _Atomic makes the load/store legal and well-defined under concurrency; a plain bool here would be a data race.

std::atomic<T> requires T to be trivially copyable; you cannot make an arbitrary class atomic by wrapping it, and an 'atomic' big struct may secretly take a lock, killing the lock-freedom you assumed.

Also called
std::atomicRust AtomicU32原子型別