Skip to content
IT glossary
ProgrammingUpdated December 3, 2026

Mutex

Мьютекс

A mutex acts like a lock for shared data. While one thread holds it, other threads must wait before entering any section of code that requires the same lock.

What a mutex protects

A mutex, short for mutual exclusion, lets one thread at a time run code guarded by that lock. That code is called a critical section. Consider a cache: if two threads both check for a key and find it missing, both may try to create an entry. Locking only the insertion doesn't fix the problem, because the decision to insert was made before either thread acquired the lock. The critical section needs to include both the check and the update.

What happens when a thread locks it

With a blocking lock call, a thread that finds the mutex held cannot proceed until it acquires the lock. A typical mutex has an owner: the thread that acquires it is responsible for releasing it. Unlocking also provides a synchronization guarantee: the next thread to acquire the same mutex can see the changes made by the previous holder before it unlocked.

The mutex doesn't know which data it's guarding. The program establishes that relationship by using the same mutex for every conflicting access. Adding a new lock to just one function won't help if another function accesses that same state without following the locking rule.

Example: removing work from a queue

#include <mutex>
#include <optional>
#include <queue>

std::mutex jobs_mutex;
std::queue<int> jobs;

std::optional<int> take_job() {
    std::lock_guard<std::mutex> lock(jobs_mutex);
    if (jobs.empty()) return std::nullopt;
    int job = jobs.front();
    jobs.pop();
    return job;
}

The empty check and removal happen under one lock, so another worker can't remove the last job between those steps. Code that pushes jobs must also acquire jobs_mutex. In C++, std::lock_guard releases the mutex when it goes out of scope, including on an early return or during exception unwinding. The caller can process the returned job without holding the lock.

Common mistakes

Keep the lock held long enough to preserve the relationship between operations, but release it before unrelated work such as a network call. If several mutexes are needed, acquire them in a consistent order. Otherwise, one thread might hold A and wait for B while another holds B and waits for A: neither can proceed, which is a deadlock.

A mutex isn't always the simplest choice. An atomic increment may be enough for a standalone counter. A counting semaphore is a better fit when the goal is to allow up to a fixed number of concurrent operations rather than give one thread exclusive access.

In interviews

Expect to be asked where the critical section starts and ends, not just where to add a lock. Walk through an interleaving that breaks the unlocked code, then explain why your lock rules out that interleaving. If you shorten the critical section, identify which operations must still stay together.