A race condition is a situation in which a system’s behavior depends on the relative timing or ordering of events, and an allowed ordering can produce an unintended result. The competing events may be instructions executed by different threads, requests arriving at a service, operations on a file, or electrical signals propagating through a circuit. A race does not require events to occur at exactly the same instant: an unfortunate sequence of individually completed actions can be sufficient.
Race conditions are a central problem in concurrent computing, where independently progressing activities must preserve shared rules. They can cause lost updates, inconsistent records, crashes, unauthorized access, or incorrect hardware state transitions. Their intermittent character makes them difficult to reproduce: a program may appear reliable under ordinary testing and fail only under a particular workload, processor configuration, or network delay.
The term encompasses several related but distinct phenomena. A data race concerns unsynchronized conflicting memory accesses; a higher-level race may occur even when every individual access is properly synchronized. In digital hardware, races concern the relative arrival of signals and the resulting state or output. Understanding these distinctions is essential because the mechanisms that prevent one kind of race may leave another untouched.
Event ordering and the meaning of correctness
A race condition is defined relative to a requirement, not merely by the existence of multiple possible execution orders. A server may legitimately process two independent requests in either order. A race arises when an ordering that the system permits violates a rule—for example, allowing two customers to purchase the same final seat, returning a partially initialized object, or deleting a resource while another operation still uses it. Nondeterminism is therefore not itself an error. The relevant question is whether every permitted execution satisfies the intended specification.
A simple example is a shared counter initially equal to zero. Two workers each execute an operation conceptually described as “read the counter, add one, and write the result.” If both read zero before either writes, both calculate one and both store one. The final value is one rather than two. This is a lost update. Each worker’s local calculation is correct, but the combined execution violates the requirement that each increment contribute exactly once. The vulnerable interval is the period between reading the old value and committing the new one.
Execution order is often described through a happens-before relation, a partial order expressing which events are ordered before others. Leslie Lamport’s 1978 paper on time and event ordering in distributed systems provided an influential formulation: events within a process follow program order, sending a message precedes its receipt, and these relations compose transitively. Programming-language memory models use related, precisely defined relations to describe synchronization. Events lacking such an ordering may be concurrent in the formal sense even when they occur at different wall-clock times.
Correctness can require more than ordering individual reads and writes. Suppose one operation checks whether a queue is nonempty and then removes an element. Another consumer may empty the queue between those two actions. Both queue methods may be individually thread-safe, yet their composition is not an indivisible “remove if available” operation. This is often called an atomicity violation. An order violation, by contrast, occurs when an action such as using a service is permitted before a necessary action such as initialization has finished.
Races differ from deadlock, in which activities cannot proceed because each awaits a condition that others cannot satisfy. A race generally concerns which execution occurs; deadlock concerns the absence of further progress. The two can nevertheless interact: introducing locks to eliminate a race can create a deadlock if lock acquisition orders conflict. This distinction separates safety requirements—nothing incorrect happens—from progress requirements—useful work eventually happens.
Shared memory, data races, and memory models
In shared-memory software, multiple threads may access the same objects within a process. A data race typically involves conflicting accesses to the same memory location, at least one of which modifies it, without the ordering required by the language’s memory model. Exact definitions vary between languages. Two reads do not constitute a data race merely because they overlap, while a read and a write may do so even if the processor happens to execute them sequentially during one particular run.
The distinction between a data race and a general race condition is fundamental. Replacing a shared counter with an atomic variable can eliminate the data race on that counter. However, the sequence “atomically read the value, calculate a replacement, atomically store it” can still lose updates. An atomic read–modify–write operation is needed to make the whole increment indivisible. Likewise, two separately atomic account balances do not automatically make a transfer between accounts an atomic operation. Data-race freedom is an important property, but it is not a complete application specification.
The memory model defines what values reads may observe and which transformations implementations may perform. Source-code order alone is insufficient because a compiler can reorder or eliminate operations when the language permits it, and a processor can use buffering and speculative execution. A cache coherence protocol coordinates copies of memory locations, but coherence does not by itself establish all the cross-location ordering a concurrent algorithm needs. A write to a “ready” flag and a write to the associated data must be connected by an appropriate publication protocol.
In C and C++, language-defined data races involving ordinary non-atomic objects generally produce undefined behavior. The C11 and C++11 standards introduced explicit facilities for atomic objects and memory ordering, making these concerns part of the standardized language model. Undefined behavior means that reasoning from a simple instruction-interleaving model may no longer be valid: the implementation is not required to preserve an intuitive “whichever thread ran last” result. Marking an object volatile does not establish interthread synchronization in these languages.
Java takes a different approach: data races do not generally make the entire execution undefined, but observations remain governed by the Java Memory Model. That model was substantially revised through JSR-133 in Java 5, released in 2004. Java’s volatile has synchronization semantics that C and C++ volatile do not share. These differences make language-specific reasoning essential. Even within one language, safe publication, object lifetime, and the protection of multi-object invariants require more than assuming that an aligned machine-word access is indivisible.
Synchronization and atomic operations
The most familiar way to prevent a shared-state race is synchronization through a mutex. A mutex establishes mutual exclusion: only one participating thread may execute the protected region at a time. If every access that can affect a shared invariant follows the same locking discipline, an operation can inspect and update the relevant state without interference. The important unit is the invariant, not necessarily a single variable. A collection’s length, storage pointer, and element contents may all need protection under one protocol.
Locks also establish memory visibility relationships. Unlocking a mutex and subsequently acquiring it in another thread can order earlier writes before later reads according to the language and library rules. A lock used around only the writer is therefore insufficient if readers bypass it. Similarly, protecting related variables with unrelated locks can permit observations of inconsistent combinations. Reader–writer locks allow multiple readers or one writer, but the programmer must correctly distinguish operations that merely inspect state from those that modify it, including hidden mutations such as cache updates.
Atomic operations provide indivisible actions on particular objects. Common primitives include fetch-and-add, exchange, and compare-and-swap, which conditionally replaces a value only if it still matches an expected value. A compare-and-swap loop can implement an update by reading a value, computing a replacement, and retrying if another thread changes the value first. This prevents the simple lost-update problem without placing a conventional mutex around the operation. It does not automatically solve problems involving several objects or the lifetime of referenced memory.
Memory ordering remains important even when all relevant accesses are atomic. A release operation can publish earlier writes, and an acquire operation that observes the appropriate publication can make those writes available to the acquiring thread. Relaxed atomic operations provide atomicity without imposing the same general ordering on surrounding accesses. Sequentially consistent atomics provide a stronger common ordering for those operations, but cannot make an arbitrary sequence of them one indivisible transaction. Choosing an ordering requires reasoning about the full communication protocol.
Lock-free algorithms introduce further difficulties. In the ABA problem, a location changes from value A to B and back to A, so a comparison against A succeeds even though relevant intervening changes occurred. If A is a pointer, the referenced storage may have been removed and reused. Techniques such as version tags, hazard pointers, and epoch-based reclamation address different aspects of this problem. Garbage collection can reduce some reclamation hazards but does not remove all logical ABA problems. Progress guarantees and race freedom remain separate properties: an algorithm may avoid locks yet still be incorrect, or preserve safety while allowing an individual thread to starve.
Asynchronous execution and resource lifetime
Race conditions do not require multiple processor cores or simultaneously executing threads. In asynchronous programming, an operation may yield while waiting for input, allowing another operation to change state before the first resumes. A single-threaded event loop prevents simultaneous execution of ordinary callbacks on that loop, but it does not make a workflow spanning several callbacks or suspension points atomic. The interval between starting an operation and handling its completion remains open to interference.
A common example occurs in a search interface. A user submits query A and then query B. Both requests are valid, but B’s response arrives first. If the interface displays each response as it arrives, A’s later response may overwrite the more recent result. No shared-memory data race is necessary: every callback can run sequentially on one thread. The violated invariant is that the display should correspond to the latest relevant query. Request sequence numbers or generation identifiers can distinguish a currently applicable response from an obsolete one.
Cancellation introduces a related race. Requesting cancellation does not necessarily mean that work has stopped, that a callback cannot run, or that a remote service has not already performed an action. A cancellation request and a completion notification may cross. An operation therefore needs defined states and transitions—for example, pending, completing, completed, or cancelled—and a rule determining which event claims the transition. Without such a rule, cleanup can run twice, a promise can be resolved twice, or a completed operation can be incorrectly reported as cancelled.
Resource lifetime is especially sensitive to interleaving. A thread may obtain a pointer just before another thread frees the object, producing a use-after-free defect. An asynchronous callback may similarly retain access to an object after its owner has closed it. Reference counting helps only when acquiring the reference is itself safe: incrementing a count through a pointer that may already be invalid does not repair the lifetime race. The protocol must ensure that obtaining a usable reference and withdrawing the last owning reference cannot conflict unsafely.
Interrupts and signal handlers provide another source of concurrency. A handler can interrupt ordinary code while a data structure is temporarily inconsistent and then access that structure itself. An operating system kernel may consequently need different synchronization rules for ordinary threads, interrupt context, and device completion handlers. Device drivers must also coordinate with hardware that accesses memory independently. Disabling local interrupts addresses only particular interleavings; it does not generally stop another processor or an external device from modifying shared state.
Database transactions and distributed services
In a database, races are often expressed as anomalies among transactions rather than individual memory accesses. A transaction groups operations into a unit, but its protection depends on the isolation level and the database’s implementation. A transaction that reads a quantity and later writes a computed replacement may still conflict with another transaction doing the same thing. The ACID properties describe broad transactional goals; invoking transactions alone does not establish that every application-level invariant is preserved.
A useful distinction is between lost updates and write skew. Suppose a schedule requires at least one of two employees to remain on call. Two transactions each read that both employees are on call. One removes the first employee, while the other removes the second. Because they update different rows, some isolation mechanisms can allow both to commit, leaving nobody on call. Each transaction was locally consistent with its snapshot. Preventing this anomaly requires a mechanism that captures the joint constraint, such as serializable isolation or appropriate explicit locking.
Serializability means that the outcome of committed transactions is equivalent to some serial execution. It does not necessarily require the transactions to run one at a time internally. A database can use locks, validation, or dependency tracking to determine whether concurrent execution is safe, aborting transactions when necessary. Constraints are another important mechanism: a uniqueness constraint can prevent duplicate identifiers even when two requests simultaneously observe that an identifier is absent. A preliminary application-level check alone cannot provide the same guarantee.
In distributed systems, network delays and partial failures widen the scope of races. A client may time out after a server has committed an operation but before the acknowledgment arrives. Retrying can then execute the operation twice. Idempotence makes repeated application have the same effect as one application, while an idempotency key can identify retries of the same logical request. Correct deduplication requires coordination between recording the key and performing the protected effect; storing them independently creates another failure window.
Linearizability is a consistency property under which each operation appears to take effect at a single point between invocation and response, respecting the real-time order of nonoverlapping operations. It is distinct from database serializability, which does not by itself impose that real-time ordering. Distributed leases and locks need equally careful treatment: a client whose lease expires may continue executing after a new owner takes over. Fencing tokens—monotonically increasing ownership identifiers checked by the protected resource—can allow that resource to reject obsolete owners. A lock service alone cannot prevent stale work if the destination accepts it unconditionally.
Security-sensitive races
Race conditions become security vulnerabilities when an attacker can influence timing or shared state to cross an authorization or integrity boundary. A program may correctly verify a condition at one moment but act on a different state later. The attacker need not control the scheduler precisely; repeated attempts, workload manipulation, or deliberately delayed responses may make a narrow vulnerable interval exploitable. Security analysis therefore considers what another participant can change between a check and the operation that depends on it.
The classic pattern is time-of-check to time-of-use, commonly abbreviated TOCTOU. A privileged program might check a pathname’s ownership or accessibility and then open that pathname. Between the two operations, another process can replace a directory entry or symbolic link. The later lookup may then identify a different object from the one checked. The defect is not that either filesystem operation is individually incorrect; it is that the program assumes the name continues to designate the same object.
A more robust design obtains a stable handle and evaluates the relevant properties of the opened object, or uses an operation that combines the necessary test with the requested action. On systems providing POSIX interfaces, exclusive file creation using the appropriate open flags can avoid the “check that a file does not exist, then create it” race. Descriptor-relative operations can also reduce dependence on mutable global path resolution. Each interface still has defined limits: handling the final path component does not necessarily address changes in every ancestor directory.
Application-level access control can fail in comparable ways. A service may authorize a request, then act after the relevant ownership, session state, or resource version has changed. Whether that is a vulnerability depends on the authorization policy: some systems intentionally authorize an operation at acceptance time, while others require permission at commitment time. A precise policy must determine which event matters. Transactions, version checks, or capability-based references can connect the authorization decision to the object and state actually used.
Commercial workflows provide further examples. Two simultaneous redemption requests can both observe an unused coupon and both apply its benefit unless redemption is recorded atomically with the effect. Similar patterns affect inventory, withdrawal limits, and account quotas. The Linux Dirty COW vulnerability, disclosed in 2016 as CVE-2016-5195, demonstrated a different class of security-sensitive race involving copy-on-write memory handling and the ability to modify mappings that should have remained protected. Such cases show that races can occur at both business-logic and kernel-memory levels, with different mechanisms but the same dependence on an insufficiently constrained execution order.
Races in digital hardware
In digital circuits, signals require nonzero time to propagate through wires and logic gates. When different paths have different delays, a logically correct expression can temporarily produce an unintended output. Such timing behavior is related to software races but is analyzed using circuit states, propagation delays, and sampling requirements rather than thread schedules. A finite-state machine implemented in hardware can reach different states if competing internal transitions occur in an unintended order.
Asynchronous sequential circuits provide a classical setting. If a transition requires more than one state variable to change, the variables may not change simultaneously. A critical race occurs when their relative order can determine the eventual stable state; a noncritical race does not change the intended final state, although intermediate states may differ. State assignment can reduce these problems by arranging permitted transitions so that only one state variable changes at a time. This makes the physical implementation’s transition structure part of the correctness argument.
A logic hazard is a related but distinct phenomenon. A static hazard briefly changes an output that should remain constant, while a dynamic hazard makes an output change multiple times when it should change once. For example, in an implementation of
setting makes the ideal Boolean output remain one as changes. Unequal delays along the two paths can nevertheless produce a short low pulse. Adding a suitable redundant term, , can remove that particular static hazard in the corresponding two-level implementation.
Synchronous design limits many timing problems by arranging for state to be sampled at clock edges. A flip-flop requires its input to remain stable during specified setup and hold intervals around the sampling event. Signals may glitch during a clock period without affecting the stored result if they settle in time and do not influence other timing-sensitive inputs. Clock skew, excessive path delay, or insufficient minimum delay can violate these assumptions. Synchronous circuitry therefore constrains timing rather than eliminating its physical significance.
When a signal crosses between unrelated clock domains, it may change near a receiving clock edge and induce metastability, in which a storage element takes an unusually long time to resolve to a valid logic level. Metastability is not simply another name for a race, but it is a major consequence of uncertain event timing. Synchronizer chains reduce the probability that unresolved behavior propagates, while multibit transfers generally require protocols such as handshakes or asynchronous queues. Independently synchronizing each bit of a changing word does not ensure that the receiver observes a coherent word.
Detection, verification, and engineering limits
Race detection is difficult because tests observe only a subset of possible executions. For threads each performing ordered steps, the number of interleavings that preserve each thread’s internal order is
This simplified count ignores many real constraints, but illustrates how rapidly schedules multiply. Many interleavings are equivalent or infeasible, while a small number may expose a defect. Increased test duration can improve coverage without proving that every relevant ordering has been examined.
Dynamic data-race detectors instrument memory accesses and synchronization operations. Some track whether conflicting accesses are ordered by happens-before; others use lockset-based reasoning or combine techniques. ThreadSanitizer is a widely used example, integrated into compiler toolchains including LLVM/Clang. Helgrind, part of Valgrind, also analyzes thread interactions. Such tools can identify unsynchronized accesses on executed paths, but their effectiveness depends on the operations they observe and the synchronization patterns they understand. Unusual custom synchronization or uninstrumented code can complicate interpretation.
Static analysis examines source code or intermediate representations without requiring the particular failing execution. It can track shared objects, lock ownership, possible aliases, and calling relationships. Precision is difficult because the analysis must approximate runtime behavior. A conservative tool may report interactions that cannot actually occur, while a more selective tool may miss real defects. Language mechanisms can move some checking into compilation: ownership and borrowing rules can prevent broad classes of unsafe sharing, although logical races remain possible in programs that are memory-safe and data-race-free.
Systematic scheduling and model checking explore execution choices more deliberately than ordinary stress testing. Partial-order reduction avoids exploring every rearrangement of independent operations, while bounded techniques restrict the number of steps, threads, or scheduling changes. Formal verification can establish properties relative to an explicit model and stated assumptions. For concurrent objects, checking linearizability can reveal failures that a data-race detector would not report, because all individual accesses may be synchronized while the combined history remains invalid.
Diagnosis also depends on observability. Logging can change timing enough to hide a failure, so a defect may disappear under a debugger or reappear only in an optimized build. Recorded histories, operation identifiers, synchronization traces, and deterministic replay can help reconstruct relevant event orderings. Wall-clock timestamps alone may be insufficient, particularly across machines whose clocks are not perfectly aligned. A race report or failure trace therefore needs interpretation in terms of actual synchronization and application invariants, rather than merely which timestamp appears earlier.