Mutex vs Atomic#

The two foundational primitives for eliminating Data Races in shared-memory concurrency are Mutexes and Atomic operations. They differ fundamentally in the scope of state they can protect and how they handle contention.


1. Core Comparison#

DimensionMutexAtomic
Protected ScopeMultiple variables, multi-statement blocks, entire composite data structuresA single scalar or pointer variable, a single operation
Contention BehaviorOS kernel or runtime scheduler blocks the contending thread and performs a Context SwitchNever sleeps; completes directly via a single CPU hardware instruction (eg. LOCK XADD, Lock-free)
Typical CostMicroseconds under contention (kernel transition and scheduling overhead)Nanoseconds (hardware cache-coherency protocol overhead)
Typical Use CasesLinked-list/map mutations, multi-field invariantsSingle counters, state flags, reference counting

2. Shared Rule: Every Access Path Must Synchronize#

A common misconception is that only Writers modifying a variable need Mutexes or Atomic operations while Readers can read the variable plainly without synchronization.

  • One-sided synchronization is still a Data Race: Even if every Writer uses a Mutex or an Atomic write, an unsynchronized plain read on the Reader side remains vulnerable to Torn Reads, stale per-core caches, and compiler/CPU instruction reordering.
  • Every concurrent read and write path touching the shared variable must use the same synchronization discipline — either all guarded by the same Mutex, or all accessed through Atomic operations.

Language Design Comparison for Preventing Accidental Plain Access#

  • Function-based APIs (eg. legacy Go sync/atomic.AddUint64(&x, 1)): Operate on an ordinary uint64 variable, so accidentally writing a plain read v := x elsewhere compiles cleanly while introducing a silent Data Race.
  • Type-enforced APIs (eg. C11 _Atomic, C++ std::atomic<T>, Go 1.19+ atomic.Uint64): Encode atomicity in the variable’s type itself, preventing accidental non-atomic accesses at compile time. See C stdatomic.

3. Selection Criteria and Real-World Contrast#

1. When a Mutex Is Required: Multi-Variable Invariants#

Whenever two or more fields must change together to preserve a structural invariant, single-variable Atomics cannot group them into one indivisible transition.

Real-world example — appending a node to a doubly linked list (HAMi-core allocator.c#L151-L163):

int add_chunk_only(CUdeviceptr address, size_t size, CUdevice dev) {
    allocated_list_entry *e;

    // LIST_ADD updates head, tail, prev, next, and length together;
    // single-variable Atomics cannot guard this multi-field invariant, so a Mutex is required
    pthread_mutex_lock(&mutex);
    if (new_allocated_list_entry(&e, 0, size, dev) != 0) {
        pthread_mutex_unlock(&mutex);
        return -1;
    }
    e->entry->address = address;
    LIST_ADD(device_overallocated, e);
    pthread_mutex_unlock(&mutex);
    return 0;
}

2. When Atomics Fit: Independent Single-Variable Operations#

When incrementing a standalone counter or reading/updating a single flag with no cross-field invariant, Atomics avoid Lock acquisition and Context Switch overhead entirely.

Real-world example — accumulating a single memory usage counter (HAMi-core multiprocess_memory_limit.c#L518):

// Atomic addition and atomic load on a single 64-bit counter
atomic_fetch_add_explicit(&slot->used[dev].total, usage, memory_order_release);
uint64_t used = atomic_load_explicit(&slot->used[dev].total, memory_order_acquire);