Concurrency Programming (6): How Atomic Operations Are Implemented — From Runtime to CPU

Traces the implementation paths of Java AtomicInteger, Go sync/atomic, and CPython's internal atomic operations to show how atomic RMW, CAS, and memory ordering reach the CPU.

EnglishPublished 5 min read
Concurrency Programming (6): How Atomic Operations Are Implemented — From Runtime to CPU

Table of Contents


0. What Does This Article Answer Next?

The previous article examined how atomic operations provide Atomicity, Visibility, and Ordering through the rules of language memory models.

This article goes deeper: how do Java, Go, and CPython implement these guarantees at the runtime and CPU layers?


1. How Does HotSpot Implement AtomicInteger?

1.1 Layers

Java Source Code
Example: AtomicInteger.incrementAndGet() / compareAndSet() / get()
Role: express atomic operations
        │
        ▼
JVM Bytecode
Example: invokevirtual AtomicInteger.incrementAndGet() / compareAndSet() / get()
Role: invoke AtomicInteger methods; there is no dedicated bytecode for atomic operations
        │
        ▼
JVM Implementation (HotSpot)
Example: Intrinsic / C1 / C2
Role: lower atomic operations to the target architecture
        │
        ▼
x86-64 Hardware
Example: Atomic Instruction / Cache Coherence / Fence
Role: provide the hardware basis for Atomicity, Visibility, and Ordering

1.2 End-to-End Implementation Path for AtomicInteger

Mermaid 图表

The main atomic operations can be expanded as follows:

Mermaid 图表

1.3 Guarantees at the Runtime / Language Implementation Layer

1.3.1 Atomicity

At the Runtime / Language Implementation layer, Atomicity is preserved through two kinds of indivisible operations:

Atomic Add
  → Unsafe.getAndAddInt
  → HotSpot Intrinsic / C1 / C2
  → Atomic Get-And-Add

CAS
  → Unsafe.compareAndSetInt
  → HotSpot Intrinsic / C1 / C2
  → Atomic CAS

HotSpot preserves their atomic semantics through compilation and lowering; the target architecture then provides the concrete machine instructions.

1.3.2 Visibility and Ordering

Visibility and Ordering depend on HotSpot preserving these memory effects:

Write side: Atomic Add / CAS
Read side: volatile read

The JMM / VarHandle memory effects define the memory semantics of these operations. HotSpot must preserve the corresponding ordering constraints during compilation and optimization.

1.4 Guarantees at the Hardware Layer

At the hardware layer, CPU cache coherence and memory ordering implement these guarantees.

For Java, the mapping to the hardware model in the first article is:

Atomicity
  → Atomic Instruction
  → HotSpot / x86-64: LOCK XADD / LOCK CMPXCHG

Visibility
  → Cache Coherence
  → Typical x86-64 CPUs: MESI-family (e.g. MESIF / MOESI)

Ordering
  → Fence / equivalent ordering constraints
  → x86-64 memory ordering + LOCKed RMW / Load rules

For implementation details, see OpenJDK’s AtomicInteger.java, Unsafe.java, vmIntrinsics.hpp, c1_GraphBuilder.cpp, and c2compiler.cpp.


2. How Is sync/atomic Implemented in Go?

2.1 Layers

Go Source Code
Example: atomic.Int64.Add() / CompareAndSwap() / Load()
Role: express atomic operations
        │
        ▼
Go Implementation
Example: sync/atomic + internal/runtime/atomic
Role: implement the atomic API and target-specific atomic primitives
        │
        ▼
x86-64 Hardware
Example: Atomic Instruction / Cache Coherence / Fence
Role: provide the hardware basis for Atomicity, Visibility, and Ordering

2.2 End-to-End Implementation Path for atomic.Int64

Mermaid 图表

The main atomic operations can be expanded as follows:

Mermaid 图表

2.3 Guarantees at the Runtime / Language Implementation Layer

2.3.1 Atomicity

At the Runtime / Language Implementation layer, Atomicity is represented by Go’s atomic primitives:

Atomic Add
  → sync/atomic
  → internal/runtime/atomic.Xadd64

CAS
  → sync/atomic
  → internal/runtime/atomic.Cas64

These operations already carry indivisible atomic semantics at this layer; the target architecture provides the concrete machine instructions.

2.3.2 Visibility and Ordering

Visibility and Ordering depend on the Go implementation preserving atomic semantics:

Write side: Xadd64 / Cas64
Read side: Load64

The Go Memory Model defines the synchronization and ordering semantics of atomic operations. The compiler and Runtime must preserve those semantics.

2.4 Guarantees at the Hardware Layer

At the hardware layer, CPU cache coherence and memory ordering implement these guarantees.

For Go, the mapping to the hardware model in the first article is:

Atomicity
  → Atomic Instruction
  → Go / x86-64: LOCK XADDQ / LOCK CMPXCHGQ

Visibility
  → Cache Coherence
  → Typical x86-64 CPUs: MESI-family (e.g. MESIF / MOESI)

Ordering
  → Fence / equivalent ordering constraints
  → x86-64 memory ordering + LOCKed RMW / Load rules

For implementation details, see sync/atomic/type.go, sync/atomic/asm.s, and internal/runtime/atomic/atomic_amd64.s.


3. How Does CPython Implement Internal Atomics?

Python’s standard library has no general-purpose integer atomic API equivalent to AtomicInteger or atomic.Int64, so this section starts inside the CPython runtime.

3.1 Layers

CPython Runtime Source Code
Example: internal shared-state updates
Role: call internal atomic operations
        │
        ▼
CPython Implementation
Example: _Py_atomic_* + GCC / Clang __atomic_*
Role: implement atomic operations and memory-order semantics, then lower them to the target architecture
        │
        ▼
x86-64 Hardware
Example: Atomic Instruction / Cache Coherence / Fence
Role: provide the hardware basis for Atomicity, Visibility, and Ordering

3.2 End-to-End Implementation Path for CPython Atomics

Mermaid 图表

The main internal atomic operations can be expanded as follows:

Mermaid 图表

3.3 Guarantees at the Runtime / Language Implementation Layer

3.3.1 Atomicity

At the Runtime / Language Implementation layer, CPython expresses Atomicity through its internal atomic abstraction and the compiler’s atomic builtins:

Atomic Add
  → _Py_atomic_add_*
  → __atomic_fetch_add

CAS
  → _Py_atomic_compare_exchange_*
  → __atomic_compare_exchange_n

These operations carry explicit atomic semantics before the compiler selects the final instruction sequence for the target architecture.

3.3.2 Visibility and Ordering

Visibility and Ordering correspond to the atomic write and read boundaries in the flowchart:

Write side: Atomic Add / CAS
Read side: Atomic Load

_Py_atomic_* passes the memory order to GCC / Clang’s __atomic_* builtins, preserving the corresponding ordering semantics at the implementation layer.

3.4 Guarantees at the Hardware Layer

The compiler then maps these atomic operations and memory orders to the target architecture.

For CPython, the mapping to the hardware model in the first article is:

Atomicity
  → Atomic Instruction
  → x86-64: LOCK XADD / LOCK CMPXCHG

Visibility
  → Cache Coherence
  → Typical x86-64 CPUs: MESI-family (e.g. MESIF / MOESI)

Ordering
  → Fence / equivalent ordering constraints
  → x86-64 ordering rules + compiler-selected instruction sequence

This describes the CPython runtime’s implementation; it does not turn those details into a memory model for Python application code.

For implementation details, see pyatomic.h and pyatomic_gcc.h.


4. The Common Pattern Across the Three Implementations

After examining Java, Go, and CPython, we can set aside the specific APIs: atomic operations perform essentially the same tasks.

4.1 How Does a Single-Variable Update Become Indivisible? — Atomic RMW

An ordinary read → modify → write consists of three separate steps:

Load
  ↓
Modify
  ↓
Store

Other execution units can interleave with those steps. For example, both CPUs can read the old value and overwrite one another’s increment:

CPU A                       CPU B
Load 0                      Load 0
Add 1                       Add 1
Store 1                     Store 1

Atomic Add, Exchange, CAS, and other atomic RMW operations make the shared-state update indivisible:

Atomic RMW
   ├── Add
   ├── Swap
   └── CAS

At the lowest level, CPU atomic instructions carry out these operations.

4.2 What Happens When a Conditional Update Fails? — CAS / Retry

With Atomic Add, two competing increments both take effect, regardless of their order:

counter = 0
CPU A                       CPU B
Atomic Add
0 → 1
                            Atomic Add
                            1 → 2

CAS behaves differently: when both CPUs compare against the same expected value, only one can succeed:

CPU A                       CPU B
CAS 0 → 1                   CAS 0 → 1
    │                           │
    ▼                           ▼
  success                     failed

When CAS fails, the higher-level code decides what to do:

CAS
 │
 ├── success ──> done
 │
 └── failed
       │
       ├── return false
       │
       └── reload → retry

Atomic operations therefore do not follow the fixed Spin → Park → Wakeup path of a mutex. Add completes an atomic update directly; CAS returns failure when it fails, leaving the decision to retry to higher-level code.

4.3 Why Can Atomics Also Establish Visibility and Ordering?

Atomicity guarantees only that this update cannot be split apart.

Ordinary reads and writes around an atomic operation must also satisfy the memory ordering specified by the higher layers:

earlier ordinary writes
      │
      ▼
Atomic Update
      │
      ▼
Atomic Read
      │
      ▼
later ordinary reads

Three layers implement this relationship:

Language / Runtime Memory Semantics
        ↓
Compiler Ordering
        ↓
Hardware Memory Ordering + Cache Coherence

Despite their different APIs, all three implementations ultimately address the same three concerns:

make each update indivisible
        +
handle conflicts
        +
preserve the required order of surrounding memory accesses

4.4 How Do Atomics Differ from Mutexes?

The simplest distinction is:

An atomic operation makes one shared-state operation indivisible; a Mutex protects a block of code.

4.4.1 One State Update, Two Approaches

Suppose all we need is to increment one counter.

With a Mutex:

Lock
  ↓
counter++
  ↓
Unlock

With an Atomic:

Atomic Add(counter, 1)

The Mutex approach is:

let one execution unit enter
        ↓
run the protected code
        ↓
leave the critical section

The Atomic approach is:

make this update itself
indivisible

If the problem is truly one Add, CAS, Swap, Load, or Store, there is no need to wrap that atomic operation in an additional critical section.

4.4.2 Why Can’t Multiple Atomics Replace One Mutex?

Suppose one logical operation must update two pieces of state:

balance -= 100
count++

Making both variables atomic gives us:

Atomic balance -= 100
        ↓
        ← another thread may observe this intermediate state
        ↓
Atomic count++

Each update is indivisible on its own, but the two updates are not atomic as a group.

A Mutex can protect both updates as one critical section:

Lock
  ↓
balance -= 100
count++
  ↓
Unlock

Until that critical section completes, another contender cannot enter the same protected region.

So once the requirement changes from “update one state” to “these steps must complete together,” a Mutex usually expresses the intent more directly.

4.4.3 Which Should You Use?

Look at what needs protection:

one state operation
Add / CAS / Swap / Load / Store
        ↓
      Atomic
a block of logic
read → decide → update multiple states
        ↓
      Mutex

The two are not independent. A Mutex commonly uses atomic operations or CAS internally to decide who acquires the lock:

Atomic / CAS
    ↓
compete for lock state
    ↓
Mutex
    ↓
protect a critical section

So the relationship can be summarized as:

Atomic: one shared-state operation
Mutex:  a critical section built on lower-level primitives such as atomic operations / CAS

5. Next: volatile

Atomic operations make RMW updates such as counter++ atomic.

If no RMW is needed, and the goal is simply to make one thread’s writes visible to another in the correct order, we reach the problem addressed by volatile.

The next article returns to language-level rules to discuss Visibility and Ordering.

Discussion

Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub