liveBook · Manning

Atomicity

As explained in Grokking Concurrency

Atomicity is the property that an operation occurs as one indivisible action, either completing entirely or not taking effect.

Imagine a shared counter being updated while several tasks are running. An atomic operation behaves like a single indivisible move: other threads see either the old value or the completed new value, never a half-finished update. section 8.6

Atomic operations are a simple synchronization technique for primitive data. Instead of acquiring a lock, changing a value, and releasing the lock, a supported hardware instruction completes the whole operation without interruption. This can reduce synchronization costs because competing tasks are not blocked. section 8.6

Use atomicity with care:

  • Treat atomicity as an environment-dependent guarantee: hardware, the runtime, and the programming language must support it. section 8.7
  • Do not assume every operation or data structure is atomic; use documented atomic types or structures when available. section 8.6
  • Use locks when an operation is not atomic, and consider message passing or avoiding shared resources when synchronization can be designed away. section 8.7 section 9.10

A hardware-level increment

An instruction such as “add 0x9082a1b, $0x1” represents an increment of a memory location. Hardware guarantees that the addition either does not happen or reaches completion, with no visible intermediate state. section 8.6

add 0x9082a1b, $0x1

Inspect the assembly-style increment that illustrates an atomic update at a specific memory address. section 8.6

How Grokking Concurrency covers it

How deep it goes
Explains all-or-nothing hardware execution and software support, but defers detailed implementation of atomic data structures.
Examples
Uses a counter increment and an assembly instruction adding one to a memory location.
What it assumes
Assumes shared resources and concurrent tasks, while defining partial visibility and synchronization in practical terms.
What you can do after
Apply atomic data structures when supported, and substitute locks or message passing when atomicity is unavailable.
How it connects
Connects atomicity with race conditions, critical sections, locks, mutexes, semaphores, and message passing.

Also explained in

Compare how 13 books explain atomicity →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Grokking Concurrency. The section links point to the parts of the book it draws on.