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.
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.
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:
- An Intro to Threading in Python (Tutorial)
- Threading in Python (Course)
- Speed Up Your Python Program With Concurrency (Tutorial)
- What Is the Python Global Interpreter Lock (GIL)? (Tutorial)
- Python 3.13: Free Threading and a JIT Compiler (Tutorial)
- Free-Threaded Python Unleashed and Other Python News for July 2025 (Tutorial)
- Thread Safety in Python: Locks and Other Techniques (Course)
- Python Thread Safety: Using a Lock and Other Techniques (Quiz)
- Python Threading (Quiz)
- Speed Up Python With Concurrency (Course)
- Python Concurrency (Quiz)
- Understanding Python's Global Interpreter Lock (GIL) (Course)
- What Is the Python Global Interpreter Lock (GIL)? (Quiz)
- Python 3.13: Free Threading and a JIT Compiler (Quiz)