Skip to content

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.

Interactive diagram — enable JavaScript to view.

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.

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 25, 2026