{
  "id": "atomic-operation",
  "title": "Atomic operation",
  "lang": "en",
  "source_lang": "en",
  "summary": "An atomic operation is an indivisible action whose intermediate states cannot be observed by other participants within a specified concurrency model.",
  "category": "computer-science",
  "subcategory": "software",
  "type": "concept",
  "aliases": [
    "Atomic action",
    "Indivisible operation"
  ],
  "generated_at": "2026-11-03",
  "model": "pro/gpt-6.1-sol",
  "url": "https://aiwiki.page/en/atomic-operation/",
  "translations": {
    "zh-Hans": {
      "url": "https://aiwiki.page/zh/atomic-operation/",
      "json": "https://aiwiki.page/zh/atomic-operation.json"
    }
  },
  "sections": [
    {
      "heading": "",
      "text": "An atomic operation is an operation that appears to take effect indivisibly with respect to other operations in a specified execution model. In concurrent computing, atomic operations allow multiple threads or processes to access shared state without observing a partially completed update. Their guarantees depend on the hardware, programming language, or interface that defines them: atomicity does not by itself imply that surrounding operations are ordered, that a larger computation is indivisible, or that an update survives a system failure."
    },
    {
      "heading": "Meaning and scope",
      "text": "Atomicity concerns what other participants can observe, not necessarily how an operation is physically executed. An atomic action may require several processor steps, a retry loop, or an internal lock. It is sufficient that its externally observable behavior satisfies the atomicity contract.\n\nFor an atomic read or write, other accesses covered by the contract cannot observe a torn value assembled from parts of different writes. For an atomic read–modify–write operation, reading the old value and replacing it with a new one form a single indivisible action: another modification cannot intervene between those two parts.\n\nThis distinction matters for operations such as incrementing a shared counter. An ordinary expression equivalent to counter = counter + 1 typically involves a read, an addition, and a write. Two threads can both read the same initial value and then write the same incremented value, losing one update. An atomic increment prevents that particular race condition.\n\nAtomicity always has a scope. An operation may be atomic:\n\n- With respect to threads accessing a particular object through a language’s atomic interface.\n- With respect to processors sharing a memory-coherent system.\n- With respect to requests handled by a storage service.\n- Within a transaction that groups several changes into one logical unit.\n\nA guarantee at one level does not automatically extend to another. For example, an atomic processor instruction need not be atomic with respect to power failure or accesses by a device outside the relevant coherence domain."
    },
    {
      "heading": "Common atomic primitives",
      "text": "Atomic primitives are basic building blocks for synchronization.\n\nPrimitive | Typical semantics\nAtomic load | Reads a value without observing a partial update.\nAtomic store | Replaces a value indivisibly.\nExchange | Stores a new value and returns the previous value as one action.\nFetch-and-add | Adds a quantity and returns the previous value.\nTest-and-set | Sets a flag and returns its previous state.\nCompare-and-swap | Replaces a value only if its current value matches an expected value.\n\nAn atomic read–modify–write is stronger than a separate atomic load followed by an atomic store. Although each of the separate operations is indivisible, another thread can modify the object between them.\n\nCompare-and-swap\n\nCompare-and-swap (CAS), also exposed through interfaces named compare-exchange, performs a conditional update. Conceptually:\n\natomically:\n    if location == expected:\n        location = desired\n        return success\n    else:\n        return failure\n\nMany interfaces also report the value observed on failure. CAS supports retry loops: a thread reads a value, computes a replacement, and attempts to install it. If another thread has changed the value, the attempt fails and the computation can be retried using the new state.\n\nSome interfaces distinguish strong and weak compare-exchange. A weak operation may fail spuriously even when the comparison would permit success, allowing efficient implementations on some architectures. It is commonly used inside a retry loop.\n\nAnother mechanism is load-linked/store-conditional. A load-linked establishes a reservation, and a later store-conditional attempts to write only if the reservation remains valid. Reservation rules vary by architecture, and store-conditional can fail for reasons other than a direct change to the target value."
    },
    {
      "heading": "Hardware implementation",
      "text": "A processor may provide atomic instructions directly through its instruction set architecture. Implementations coordinate access to the relevant memory location, often using cache-coherence mechanisms to obtain exclusive access to a cache line while an update is performed. Some circumstances require stronger interconnect or bus-level coordination.\n\nAtomic support depends on operand size, alignment, memory type, and architecture. A naturally aligned machine-word access may be atomic on one platform, while a wider or misaligned access may require special handling or may not be supported atomically at all. Source-code appearance alone does not establish such a guarantee.\n\nA compiler can implement a language-level atomic operation using:\n\n- A single hardware instruction.\n- A sequence involving conditional stores or comparison-and-retry.\n- A runtime routine, possibly using a lock.\n\nConsequently, “atomic” does not mean “one instruction” or “lock-free.” Where a language exposes whether an atomic type is lock-free, the answer may depend on its size, alignment, implementation, and target hardware.\n\nDisabling interrupts can protect some critical sections on a single processor, but it does not by itself stop another processor from accessing shared memory. Multiprocessor atomicity requires coordination beyond local interrupt control."
    },
    {
      "heading": "Atomicity and memory ordering",
      "text": "Atomicity and memory ordering are separate properties. Atomicity concerns the indivisibility of an access; ordering concerns how that access relates to other reads and writes.\n\nA memory model defines which observations are permitted during concurrent execution. In widely used language models, atomic accesses can have different ordering strengths:\n\n- Relaxed ordering preserves the atomicity of the access and the required ordering of modifications to that atomic object, but does not by itself establish synchronization for unrelated memory.\n- Acquire and release ordering can establish a synchronization relationship through an atomic object. When the required relationship holds, writes preceding a release become visible to operations following the corresponding acquire.\n- Sequentially consistent ordering additionally places sequentially consistent operations in a single total order consistent with the model’s rules.\n\nFor example, a producer can initialize ordinary data and then perform a release store to a readiness flag. A consumer that observes the published flag through a suitable acquire load can then access the initialized data, provided the program also prevents conflicting later accesses and satisfies object-lifetime requirements. Merely making the flag atomic with relaxed ordering does not establish that publication guarantee.\n\nIn the C programming language, atomic types and operations were standardized in C11; C++ introduced its standard atomic facilities in C++11. In these languages, the volatile qualifier is not a substitute for atomic operations or interthread synchronization.\n\nLinearizability is a related correctness condition for concurrent objects. A linearizable operation behaves as though it took effect at one point between invocation and completion. This is useful for reasoning about concurrent interfaces, but individual atomic accesses do not automatically make an entire algorithm linearizable or impose a single ordering on all memory accesses."
    },
    {
      "heading": "Applications and progress guarantees",
      "text": "Atomic operations are used to implement mutexes, spinlocks, reference counters, state flags, work distribution, and concurrent data structures. They are especially important in parallel computing, where many execution units access shared memory.\n\nThey also support non-blocking algorithms, whose progress guarantees are distinct from atomicity:\n\n- Obstruction-free: an operation can complete if it eventually executes without interference.\n- Lock-free: the system as a whole continues to complete operations, although an individual participant may repeatedly fail.\n- Wait-free: every operation completes within a bounded number of its own steps under the stated model.\n\nA CAS retry loop is not automatically wait-free, and an arbitrary algorithm using CAS is not automatically lock-free. Correctness and progress depend on the complete algorithm, including allocation, memory reclamation, and any other operations it invokes."
    },
    {
      "heading": "Limitations and common pitfalls",
      "text": "Compound invariants\n\nAtomicity of individual variables does not preserve a relationship involving several variables. For example, separately updating two atomic account balances does not make a transfer indivisible to other observers. Protecting such an invariant may require mutual exclusion, a transactional mechanism, or a specially designed concurrent protocol.\n\nLikewise, a check followed by an action is not atomic merely because both steps use atomic accesses. A conditional update generally requires an appropriate read–modify–write primitive or external synchronization.\n\nThe ABA problem and object lifetime\n\nIn a CAS-based algorithm, a location may change from value A to B and then back to A. A later comparison against A succeeds even though intervening changes occurred. This is the ABA problem, which is significant when the algorithm depends on the history or identity of the object rather than only its current representation.\n\nAtomic pointer updates also do not make the pointed-to object safe to access. Another thread may remove and reclaim that object. Concurrent algorithms therefore need separate lifetime-management techniques, such as hazard pointers, epoch-based reclamation, or suitable forms of garbage collection.\n\nContention and scalability\n\nFrequent atomic updates to one location can become a serialization bottleneck. Ownership of the relevant cache line may repeatedly move between processors. Independent variables sharing a cache line can also interfere with one another, a phenomenon called false sharing.\n\nAtomic operations are therefore not inherently faster than locks. Performance depends on contention, memory ordering, architecture, and the amount of work protected. A correct design using a lock can outperform a complex retry-based design."
    },
    {
      "heading": "Relationship to transactional atomicity",
      "text": "In a database transaction, atomicity generally means that a transaction’s changes are committed as a unit or do not take effect. It is one of the ACID properties. This all-or-nothing meaning is related to, but distinct from, the indivisibility of a shared-memory operation.\n\nTransaction atomicity does not by itself specify which intermediate states other transactions may observe; that is governed by isolation. Persistence after a successful commit is governed by durability. Similarly, an atomic memory store does not by itself guarantee durable storage, and a crash-safe storage update does not necessarily provide synchronization between threads."
    }
  ],
  "links": [
    "concurrent-computing",
    "thread-computing",
    "race-condition",
    "synchronization-computing",
    "central-processing-unit",
    "cache-coherence",
    "compiler",
    "memory-model",
    "c-programming-language",
    "mutex",
    "spinlock",
    "data-structure",
    "parallel-computing",
    "shared-memory",
    "mutual-exclusion",
    "garbage-collection",
    "database-transaction",
    "acid-properties"
  ],
  "sources": [],
  "license": "https://creativecommons.org/licenses/by/4.0/"
}