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:
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.
Related Resources
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.
For additional information on related topics, take a look at the following resources:
- What Is the Python Global Interpreter Lock (GIL)? (Tutorial)
- Speed Up Your Python Program With Concurrency (Tutorial)
- An Intro to Threading in Python (Tutorial)
- Python 3.13: Free Threading and a JIT Compiler (Tutorial)
- Hands-On Python 3 Concurrency With the asyncio Module (Course)
- Thread Safety in Python: Locks and Other Techniques (Course)
- Python Thread Safety: Using a Lock and Other Techniques (Quiz)
- Understanding Python's Global Interpreter Lock (GIL) (Course)
- What Is the Python Global Interpreter Lock (GIL)? (Quiz)
- Speed Up Python With Concurrency (Course)
- Python Concurrency (Quiz)
- Threading in Python (Course)
- Python Threading (Quiz)
- Python 3.13: Free Threading and a JIT Compiler (Quiz)
By Martin Breuss • Updated July 15, 2026