Skip to content

race condition

A race condition is a flaw in concurrent code where the outcome depends on the relative timing or interleaving of multiple threads or processes that access shared state, when at least one of them writes to it.

The problem appears when those accesses run without coordination. A classic case is two threads each incrementing the same counter. Reading the value, adding one, and writing it back is not a single indivisible step, so both threads can read the same starting number and store the same result, silently dropping one update, as the following interleaving shows:

Sequence diagram where Thread A and Thread B both read a shared counter as 0, each adds 1, and both write 1, so one increment is lost.
Two Increments, One Lost Update

The block of code that touches the shared state is called a critical section, and it must run under mutual exclusion so that only one thread enters at a time. Programs enforce that exclusion with synchronization primitives:

  • A mutex or lock, which lets a single thread hold a resource at a time.
  • A semaphore, which caps how many threads use a resource at once.
  • An atomic operation, which the hardware guarantees to finish in one indivisible step.

A data race is a closely related but distinct term. It names the specific case where two threads reach the same memory location without synchronization and at least one of them writes, which is one common way a race condition arises.

Because the timing that triggers a race condition rarely repeats, the resulting bugs are nondeterministic and hard to reproduce. In Python, the Global Interpreter Lock (GIL) serializes bytecode execution yet still leaves multi-step operations open to races.

Python Thread Safety: Using a Lock and Other Techniques

Tutorial

Python Thread Safety: Using a Lock and Other Techniques

In this tutorial, you'll learn about the issues that can occur when your code is run in a multithreaded environment. Then you'll explore the various synchronization primitives available in Python's threading module, such as locks, which help you make your code safe.

intermediate python stdlib

For additional information on related topics, take a look at the following resources:


By Martin Breuss • Updated July 15, 2026