critical section
A critical section is a section of code in a concurrent program that accesses a shared resource and must not run in more than one process or thread at the same time. While one thread holds it, any other that reaches the section waits, a guarantee called mutual exclusion.
The point is to prevent concurrent access from corrupting shared state. When two threads read and update the same variable or file without coordination, their operations can interleave into a wrong result, a fault called a race condition.
A synchronization mechanism guards the entrance and blocks everyone else:
- Locks and mutexes: A thread acquires the lock before the section and releases it after, so only the holder proceeds.
- Semaphores: A counter caps how many threads enter, and a count of one gives plain mutual exclusion.
- Atomic operations: Hardware instructions complete indivisibly, so a short section needs no separate lock.
Mutual exclusion is clearer in motion. With the lock on, only one thread runs the section at a time and the shared counter stays correct. Switch the guard off, and several threads read the same value and clobber each other’s writes, so updates are lost.
A critical section stays short, because time spent inside it is time other threads spend blocked. In Python, the threading module’s Lock, used as a context manager, marks the exact code that runs under mutual exclusion.
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)
- An Intro to Threading in Python (Tutorial)
- Python 3.13: Free Threading and a JIT Compiler (Tutorial)
- Threading in Python (Course)
- Understanding Python's Global Interpreter Lock (GIL) (Course)
- Thread Safety in Python: Locks and Other Techniques (Course)
- Python Thread Safety: Using a Lock and Other Techniques (Quiz)
- What Is the Python Global Interpreter Lock (GIL)? (Quiz)
- Python Threading (Quiz)
- Python 3.13: Free Threading and a JIT Compiler (Quiz)
By Martin Breuss • Updated July 25, 2026