Skip to main content

Mutex

Mutual Exclusion

Pronunciation
MYOO-teks
Updated 2 min read

Share this page

Send the link, quote the definition with a link back, or show it as a card on your own site.

https://softwaredictionary.org/terms/mutex

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

Two threads share a balance of 100, guarded by a mutex. Thread A locks it and adds 50; thread B asks for the lock meanwhile and waits; when A unlocks, B gets the lock and subtracts 20. One at a time, so the balance ends at 130 as it should.balance: 100 → 150 → 130Thread AMutexThread Block()unlock()balance += 50critical sectionfreeheld by Aheld by Bfreewaiting for the lockbalance -= 20critical sectionlock()unlock()time
Only the thread holding the mutex may run the critical section. Everyone else waits their turn, so no update is lost.

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

Protecting a shared counter in Pythonpython
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 400000

Readers 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

Spotted a mistake or something missing on this page?Suggest an edit

Read a random page
Open today's review
Switch to the dark theme
Read this page in Türkçe

More

Settings