Skip to content

Atomic variable

Category: Lock-free · Status: stub · Lessons: chapter 02, Shared state

One line: A number or pointer whose reads, writes and increments each happen as one indivisible CPU operation, so threads can share it without a lock.

Also called: atomics, atomic integer, Interlocked.

How it connects

flowchart LR
  n_atomic_variable["Atomic variable"]
  n_data_race["Data race"]
  n_interior_mutability["Interior mutability"]
  n_lock_free["Lock-free"]
  n_mutex["Mutex"]
  n_rcu["Read-copy-update"]
  n_spinlock["Spinlock"]
  n_atomic_variable ---|or| n_mutex
  n_atomic_variable -->|prevents| n_data_race
  n_interior_mutability -->|uses| n_atomic_variable
  n_lock_free -->|uses| n_atomic_variable
  n_rcu -->|uses| n_atomic_variable
  n_spinlock -->|uses| n_atomic_variable
  classDef center stroke-width:3px
  class n_atomic_variable center
  classDef outside stroke-dasharray: 4 3
  class n_data_race,n_interior_mutability,n_lock_free,n_mutex,n_rcu,n_spinlock outside

In each language

Rust std::sync::atomic: AtomicBool, AtomicUsize, AtomicPtr and more, each taking an Ordering; not every platform has every type
Go sync/atomic typed values such as atomic.Int64, atomic.Bool and atomic.Pointer, added in Go 1.19
C _Atomic and <stdatomic.h> (C11); a compiler that defines __STDC_NO_ATOMICS__ does not provide them
C++ std::atomic<T> for integers, pointers and other trivially copyable types
Java AtomicInteger and the rest of java.util.concurrent.atomic
C# Interlocked provides atomic operations for variables shared by multiple threads
JavaScript Atomics operations on typed arrays over a SharedArrayBuffer
Swift Atomic in the Synchronization module
Haskell atomicModifyIORef' modifies an IORef atomically; plain modifyIORef is not atomic

Where to read more