Mutex
Mutual Exclusion
- Pronunciation
- MYOO-teks
In short
A mutex is a lock that lets only one thread at a time enter a critical section of code, so threads can't corrupt shared data by changing it at the same time.
What is a mutex?
A mutex, short for mutual exclusion, is a synchronization tool that protects shared data from being used by several threads at once. A thread locks, or acquires, the mutex before touching the data and unlocks, or releases, it afterward. If another thread already holds the mutex, the caller waits until it is released. The code between lock and unlock is called a critical section.
Under the hood, a mutex uses atomic CPU instructions, such as compare-and-swap, to claim the lock safely, plus help from the operating system to put waiting threads to sleep instead of letting them spin and burn CPU time. A mutex has an owner: only the thread that locked it should unlock it. Most languages provide one, such as threading.Lock in Python, std::mutex in C++, sync.Mutex in Go, and Mutex<T> in Rust, which wraps the data itself so it cannot be reached without locking.
A mutex is like the single key to a coffee shop restroom: whoever has the key goes in, and everyone else waits in line until the key comes back. Mutexes protect shared counters, in-memory caches, lists of open connections, and writes to the same file.
A mutex is often confused with a semaphore. A mutex allows exactly one holder and has an owner, while a semaphore is a counter that can let several threads in at once and can be released by any thread. It also helps to keep the related bugs apart: a race condition is the bug a mutex prevents, and a deadlock is the bug careless mutex use can cause, when two threads each hold one mutex and wait forever for the other's. Keep critical sections short and release the lock automatically with constructs like with, defer, or scoped guards.
At a glance
Key takeaways
- A mutex lets only one thread at a time run a critical section.
- Threads that find the mutex locked wait until it is released.
- Only the thread that locked a mutex should unlock it.
- Mutexes prevent race conditions but can cause deadlocks if misused.
- Keep critical sections short and always release the lock, even on errors.
Example
import threading
counter = 0
lock = threading.Lock() # Python's mutex
def add_many():
global counter
for _ in range(100_000):
with lock: # acquire; released automatically at the end
counter += 1 # critical section: one thread at a time
threads = [threading.Thread(target=add_many) for _ in range(4)]
for t in threads: t.start()
for t in threads: t.join()
print(counter) # always 400000Readers ask
What is the difference between a mutex and a semaphore?
A mutex lets exactly one thread in and must be released by the thread that acquired it. A semaphore keeps a count of permits, so it can let several threads in at once, and any thread can release it.
What is a critical section?
A critical section is a piece of code that accesses shared data and must not be run by more than one thread at a time. A mutex is the usual way to guard it.
What is a spinlock?
A spinlock is a lock where a waiting thread repeatedly checks the lock in a tight loop instead of sleeping. It is efficient only when locks are held for a very short time, which is why it is mostly used inside kernels.
Often compared
See also
- SemaphoreOperating Systems, p. 26A semaphore is a synchronization tool that keeps a counter of available permits, letting up to a fixed number of threads use a resource at the same time.
- Race ConditionOperating Systems, p. 24A race condition is a bug where a program's result depends on the unpredictable timing of threads, processes, or requests that use shared data at the same time.
- DeadlockOperating Systems, p. 8A deadlock is a situation where two or more threads or processes wait forever for each other to release resources, so none of them can make progress.
- ThreadOperating Systems, p. 33A thread is the smallest unit of execution an operating system can schedule, running inside a process and sharing that process's memory with other threads.
- ConcurrencyProgramming Fundamentals, p. 12Concurrency is a program's ability to make progress on several tasks in overlapping time periods, such as serving many users at once rather than one at a time.
- Optimistic LockingDatabases, p. 32Optimistic locking is a concurrency technique that lets transactions proceed without holding locks and checks a version number at save time to detect conflicts.
Spotted a mistake or something missing on this page?Suggest an edit