{
  "id": "spinlock",
  "title": "Spinlock",
  "lang": "en",
  "source_lang": "en",
  "summary": "A spinlock is a mutual-exclusion lock that makes waiting threads repeatedly check for availability rather than suspend execution.",
  "category": "computer-science",
  "subcategory": "software",
  "type": "concept",
  "aliases": [
    "Spin lock"
  ],
  "generated_at": "2026-11-03",
  "model": "pro/gpt-6.1-sol",
  "url": "https://aiwiki.page/en/spinlock/",
  "translations": {
    "zh-Hans": {
      "url": "https://aiwiki.page/zh/spinlock/",
      "json": "https://aiwiki.page/zh/spinlock.json"
    }
  },
  "sections": [
    {
      "heading": "",
      "text": "A spinlock is a synchronization mechanism that enforces mutual exclusion by making a waiting execution context repeatedly attempt or check for lock acquisition. This repeated activity, called busy waiting or spinning, consumes processor execution resources rather than suspending the waiter until the lock becomes available. Spinlocks are used chiefly to protect short operations on shared data, particularly when the overhead of suspending and resuming a waiter would exceed the expected waiting time."
    },
    {
      "heading": "Operating principle",
      "text": "A spinlock normally has an unlocked state and a locked state. An execution context must acquire the lock before entering a critical section and release it after leaving. Other contexts following the same locking protocol cannot enter that critical section simultaneously.\n\nAcquisition requires an atomic operation: an operation whose relevant effects occur indivisibly with respect to competing accesses. Common hardware primitives include test-and-set, exchange, and compare-and-swap. A successful operation changes the lock from available to held without allowing another contender to make the same transition successfully at the same time.\n\nA naive sequence that first reads an ordinary Boolean variable and then writes “locked” is insufficient. Two contenders can both observe the unlocked state before either writes to it, producing a race condition.\n\nA basic acquisition loop behaves as follows:\n\n- Attempt to change the lock from unlocked to locked atomically.\n- If successful, enter the critical section.\n- Otherwise, repeat until acquisition succeeds.\n- Release the lock when the protected operation is complete.\n\nRelease need not use the same read-modify-write instruction as acquisition. An atomic store with the appropriate memory-ordering semantics is sufficient for many implementations."
    },
    {
      "heading": "Memory ordering and correctness",
      "text": "Preventing simultaneous acquisition is only part of a lock’s function. A lock must also make protected memory accesses visible in the required order under the relevant memory model.\n\nTypically, successful acquisition has acquire semantics, and release has release semantics. Writes performed before an owner releases the lock become visible to a subsequent owner that acquires it through the corresponding synchronization relationship. These rules constrain both compiler transformations and processor behavior.\n\nAn illustrative implementation in C, using the atomics introduced in C11, is:\n\n#include <stdatomic.h>\n\ntypedef struct {\n    atomic_flag held;\n} spinlock;\n\nspinlock lock = { ATOMIC_FLAG_INIT };\n\nvoid spin_lock(spinlock *s)\n{\n    while (atomic_flag_test_and_set_explicit(\n               &s->held, memory_order_acquire)) {\n        /* Busy wait. */\n    }\n}\n\nvoid spin_unlock(spinlock *s)\n{\n    atomic_flag_clear_explicit(\n        &s->held, memory_order_release);\n}\n\nThe test-and-set operation returns the previous flag value while setting it. A previous value of false indicates successful acquisition. C guarantees that operations on atomic_flag are lock-free, although that does not make the spinlock itself a lock-free algorithm.\n\nThis example illustrates the synchronization mechanism, not a complete production implementation. It has no fairness guarantee, no recursive acquisition support, and no processor-specific waiting optimization. Using volatile instead of atomic operations would not provide equivalent atomicity or inter-thread synchronization.\n\nCorrectness also depends on the surrounding program:\n\n- All accesses requiring protection must follow the same locking protocol.\n- The lock must be initialized before concurrent use.\n- Only the owner may release it under the usual spinlock contract.\n- Control flow must not leave the critical section without releasing the lock.\n- Nested locks must follow a consistent ordering to avoid deadlock."
    },
    {
      "heading": "Relationship to other locking mechanisms",
      "text": "A spinlock and a mutex both provide exclusive access, but the terms emphasize different properties. Spinlock describes waiting behavior; mutex describes mutual-exclusion semantics and often denotes a lock that can suspend its waiters. Some mutex implementations spin briefly before blocking.\n\nA blocking lock allows an unsuccessful waiter to stop executing so that the operating system can schedule other work. This normally involves scheduling and wake-up overhead. A spinlock avoids that transition, but the waiter continues occupying execution resources.\n\nAn adaptive or hybrid lock combines these approaches. It may spin for a bounded period, spin while the owner appears to be running, or block after repeated failed attempts. Such designs aim to handle both brief contention and longer delays.\n\nSpinning must not be confused with non-blocking progress guarantees. A spinlock is a blocking synchronization algorithm in the progress-theoretic sense: if its owner stops indefinitely, contenders may also stop making useful progress. A waiter’s continued instruction execution does not make the algorithm lock-free or wait-free."
    },
    {
      "heading": "Performance characteristics",
      "text": "Spinlocks are most attractive when critical sections are short, contention is limited, and the owner can continue running on another processor. They are commonly associated with parallel computing on shared-memory multiprocessors.\n\nWaiting cost and scheduling\n\nThe relevant comparison is between the expected cost of spinning and the cost of suspension, scheduling, and wake-up. There is no universal time threshold: the outcome depends on hardware, workload, scheduling policy, and implementation.\n\nA waiter can waste substantial processor time if the owner is preempted. On a single available processor, a running waiter cannot benefit from an owner executing simultaneously; the owner must regain execution before it can release the lock. In an oversubscribed system, excessive spinning can also delay useful work.\n\nThese effects connect spinlock behavior closely to CPU scheduling. In a virtualized environment, a guest may spin while the virtual processor holding the lock is not scheduled by the host.\n\nCache-coherence traffic\n\nA simple test-and-set loop repeatedly attempts to write the same memory location. Under contention, this can generate heavy cache-coherence traffic as processors compete for ownership of the lock’s cache line.\n\nA test-and-test-and-set implementation first polls with ordinary atomic reads and attempts the modifying operation only when the lock appears free. This often reduces coherence traffic while the lock is held. However, several waiters may still compete simultaneously when it is released.\n\nPlacement also matters. If lock state shares a cache line with unrelated frequently modified data, cache invalidations can increase contention even when the logical data accesses are independent.\n\nProcessor waiting instructions and backoff\n\nSpin loops often include an architecture-specific hint, such as an x86 PAUSE instruction. Such hints can improve spin-loop behavior, reduce resource pressure, or benefit another hardware thread sharing the core. They do not themselves provide mutual exclusion or the necessary memory ordering.\n\nBackoff schemes insert increasing or randomized delays between acquisition attempts. They can reduce repeated collisions, but may increase latency and do not inherently guarantee fairness."
    },
    {
      "heading": "Major variants",
      "text": "Test-and-set locks\n\nThe simplest spinlocks use a single shared flag and an atomic exchange or test-and-set operation. They have a small representation and a simple fast path, but can perform poorly under contention. Newly arriving contenders may repeatedly acquire the lock ahead of older waiters.\n\nTicket locks\n\nA ticket lock maintains a next-ticket counter and a currently-served counter. Each contender atomically obtains a ticket and waits until its number is served. Release advances the serving counter.\n\nTicket locks provide first-in, first-out service according to ticket allocation order. However, waiters typically poll the same serving counter, and strict ordering can cause a convoy if the next owner is delayed. Fair ordering alone does not guarantee bounded wall-clock waiting.\n\nQueue-based locks\n\nQueue-based spinlocks give contenders separate queue nodes. Each waiter generally spins on a location associated with its own node, and release explicitly hands ownership to a successor.\n\nThe MCS lock, named for John Mellor-Crummey and Michael Scott, is a prominent example. Its design limits shared-memory communication per acquisition and release, making it more scalable than simple centralized spinning under substantial contention. Queue management, node lifetime, cancellation, and preemption introduce additional complexity.\n\nOn non-uniform memory access systems, lock designs may also account for memory locality, balancing fair service against the cost of repeatedly transferring ownership between processor groups."
    },
    {
      "heading": "Operating-system use",
      "text": "Spinlocks are important inside an operating-system kernel, where some contexts cannot suspend execution. They can protect short updates to scheduler structures, interrupt-related state, and other shared kernel data.\n\nKernel spinlock interfaces often impose rules beyond mutual exclusion. Acquisition may disable preemption, and variants may disable local interrupts. These are distinct operations:\n\n- Disabling preemption prevents the current task from being displaced by ordinary task scheduling.\n- Disabling local interrupts prevents relevant interrupt handlers on the same processor from running.\n- The lock coordinates access among participating execution contexts, including those on other processors.\n\nIf an interrupt handler attempts to acquire a lock held by the code it interrupted, it can spin indefinitely because that code cannot resume to release the lock. Interrupt-safe locking protocols address this situation by controlling the relevant interrupts before acquisition.\n\nConventional non-sleeping kernel spinlock critical sections cannot call operations that may sleep. The precise rules depend on the kernel and configuration. In Linux, for example, PREEMPT_RT changes the implementation and semantics of ordinary spinlock_t locks, while raw_spinlock_t retains strict spinning behavior."
    },
    {
      "heading": "Limitations",
      "text": "Spinlocks do not inherently guarantee fairness, bounded waiting, or recovery from owner failure. A basic lock may allow starvation. Recursive acquisition by the owner usually results in self-deadlock unless recursion is explicitly supported.\n\nPriority inversion is another concern: a high-priority waiter can depend on a lower-priority owner. On a single processor, an actively spinning high-priority task may prevent that owner from running unless scheduling or locking rules prevent the situation. Strict latency requirements therefore depend on the whole synchronization and scheduling design, not merely on a short expected critical section.\n\nSpinning also consumes energy and processor capacity while accomplishing no protected work. At high contention, changing the program’s organization can matter more than changing the acquisition loop—for example, partitioning protected state, using per-processor data, or reducing the amount of work performed while holding a lock."
    }
  ],
  "links": [
    "synchronization-computing",
    "mutual-exclusion",
    "critical-section",
    "atomic-operation",
    "race-condition",
    "memory-model",
    "compiler",
    "c-programming-language",
    "deadlock",
    "mutex",
    "operating-system",
    "parallel-computing",
    "cpu-scheduling",
    "virtualization",
    "cache-coherence",
    "cpu-cache",
    "non-uniform-memory-access",
    "kernel-operating-system",
    "linux"
  ],
  "sources": [],
  "license": "https://creativecommons.org/licenses/by/4.0/"
}