Skip to content

mutex (mutual exclusion)

A mutex, or mutual exclusion lock, is a synchronization primitive that allows only one thread or process at a time to enter a critical section of code or use a shared resource.

A mutex has two states, locked and unlocked. A thread acquires the mutex before touching the shared data and releases it afterward. If the mutex is already held, the requesting thread blocks until the holder releases it, and then one waiting thread proceeds. Unlike a binary semaphore, a mutex has an owner, so only the thread that locked it may unlock it.

The following walkthrough steps through that acquire, block, and release cycle, with two threads taking turns to hold a single mutex.

Interactive diagram — enable JavaScript to view.

Mutexes prevent race conditions, but careless locking can introduce deadlock when two threads each wait on a mutex the other holds. Recursive (reentrant) variants let the owning thread acquire the same mutex more than once without blocking on itself.

In Python, the threading module provides Lock for mutual exclusion, with RLock as its reentrant counterpart. A Python Lock, however, isn’t tied to an owning thread, so any thread can release it, whereas RLock must be released by the thread that acquired it.

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 20, 2026 • Reviewed by Leodanis Pozo Ramos