Home › Categories › Concepts & Theory › Race Condition

Race Condition

From WikiTech, the encyclopedia of technology

Concept · Concepts & Theory · 5 min read · 982 words · Updated

Race Condition
Concept
CategoryConcurrency defect
DetectionThreadSanitizer, model checking
RelatedDeadlock, atomicity

A race condition is a defect in which the behaviour of a program depends on the relative timing or interleaving of events that are not properly synchronised. The result may be correct on most runs and wrong on a few, which makes these bugs notoriously hard to reproduce and diagnose.

Race conditions are most often associated with multithreaded programs that share memory, but they also occur between separate processes, between a program and the file system, and in distributed systems where several services update the same record. They are a central concern of concurrent programming and a frequent source of security vulnerabilities.

Definition and a simple example

Consider two threads that each add one to a shared counter. The operation looks atomic in source code, but at the machine level it consists of three steps: read the value, add one, write the result back. If both threads read the value before either writes, one update is lost.

Thread A: read counter (5)
Thread B: read counter (5)
Thread A: write counter (6)
Thread B: write counter (6)   <- expected 7

The final value is 6 instead of 7. Nothing crashed and no error was reported; the data is simply wrong. Run the same code again and the threads might interleave differently and give the correct answer, which is why such defects can pass testing and fail in production.

Race conditions and data races

The two terms are related but not identical.

  • A data race occurs when two threads access the same memory location concurrently, at least one access is a write, and there is no synchronisation ordering them. In languages such as C and C++ a data race is undefined behaviour, so the compiler is allowed to assume that none exist.
  • A race condition is the broader category of incorrect behaviour that depends on timing. A program can be free of data races, for example because every access is locked, and still have a race condition, such as checking a balance and then withdrawing money in two separate locked steps.

Common forms

Check-then-act

The program tests a condition and then acts on it, but the condition changes in between. A typical case is "if the file does not exist, create it". Another process may create the file in the gap. In security this pattern is known as time-of-check to time-of-use (TOCTOU) and has been exploited to trick privileged programs into modifying files that an attacker should not control.

Read-modify-write

As in the counter example, a value is read, changed and written back without protection. Database applications show the same pattern when two requests read a row, compute a new value in application code and save it, overwriting each other's work.

Ordering and initialisation

A thread may use an object before another thread has finished initialising it. Lazy initialisation of shared singletons without proper memory ordering is a classic example.

Consequences

Race conditions have caused serious real-world failures. The Therac-25 radiation therapy machine delivered massive overdoses to patients between 1985 and 1987; investigators found that a race condition in its control software was one of the contributing causes.[1] A race condition in an alarm-system software component was identified among the causes that left operators unaware of the problems preceding the 2003 North American blackout. In everyday software the effects are usually milder: lost updates, duplicated orders, corrupted caches or sporadic crashes.

Prevention

The remedies fall into a few families.

  • Mutual exclusion. Locks (mutexes) allow only one thread at a time into a critical section. They are simple but risk deadlock when threads wait for each other, and they can limit performance.
  • Atomic operations. Hardware-supported instructions such as compare-and-swap update a value indivisibly and underlie lock-free data structures.
  • Immutability. Data that never changes can be shared freely between threads.
  • Message passing. Instead of sharing memory, threads or processes communicate by sending messages, as in the actor model and Go's channels.
  • Transactions. Databases isolate concurrent changes with transactions, and optimistic concurrency control detects conflicts by checking a version number at write time.
  • Language support. Rust rejects programs that could share mutable data between threads without synchronisation, so data races cannot occur in safe code.[4]

Detection and testing

Because timing is involved, ordinary tests rarely expose race conditions. Specialised tools help. Dynamic detectors such as ThreadSanitizer and the Go race detector instrument memory accesses at run time and report conflicting accesses that lack a happens-before relationship.[2][3] Static analysis can flag suspicious patterns without running the code. Formal methods and model checkers, such as TLA+ and SPIN, explore every possible interleaving of an abstract model to find rare orderings. Stress testing with many threads, artificial delays and randomised scheduling raises the chance of hitting a bad interleaving.

Distributed settings

Races are not limited to one machine. Two clients may both read a stock level of one and both place an order. Protecting against this needs coordination: conditional writes, version checks, unique constraints, distributed locks or consensus protocols. Designing operations to be idempotent also reduces the damage when retries and duplicates interleave unexpectedly.

Common misconceptions

Adding a short sleep or a flag variable does not fix a race condition; it only changes the timing and often hides the problem until load increases. Nor does a single-core machine make races impossible, because a thread can still be preempted between any two instructions. The reliable approach is to make the required ordering explicit through synchronisation, so that correctness does not depend on luck.

Editorial connections and engineering implications

A race condition is not always a simple unsynchronised memory access. A program can protect each individual access yet still perform a logically unsafe sequence, such as checking that a file exists and then opening it after another process has changed it. The remedy may be an atomic operating-system operation rather than a mutex around unrelated code. This distinction separates broad timing-dependent failures from the narrower concept of a data race.

Distributed services face similar problems through retries, duplicate messages and out-of-order updates. Transactions, unique operation identifiers, compare-and-swap operations and idempotent handlers can reduce risk. Concurrency tests, race detectors and stress testing improve confidence, but designs should also minimise shared mutable state. These ideas connect to event-driven concurrency, retry safety and the ownership rules in Rust.

See also

  • Event Loop – A programming construct that waits for and dispatches events or messages in a single thread of control.
  • Idempotency – The property of an operation that produces the same result whether it is applied once or many times.
  • CAP Theorem – A result stating that a distributed data store cannot simultaneously guarantee consistency, availability and partition tolerance.
  • Big-O Notation – A notation describing how the resource use of an algorithm grows as the input size grows.
  • C++ – A general-purpose, statically typed language that extends C with classes, templates and zero-overhead abstractions.
  • Garbage Collection – Automatic memory management in which a runtime reclaims memory that a program can no longer reach.
  • Rust – A compiled systems programming language that enforces memory safety through ownership and borrowing without a garbage collector.
  • Domain Name System (DNS) – The distributed naming system that translates human-readable domain names into records used to locate internet services.

References

  1. ↑ Leveson and Turner (1993), An investigation of the Therac-25 accidents (sunnyday.mit.edu)
  2. ↑ Clang documentation: ThreadSanitizer (clang.llvm.org)
  3. ↑ Go documentation: Data Race Detector (go.dev)
  4. ↑ The Rust Programming Language: Fearless concurrency (doc.rust-lang.org)