aiwiki.page
English

Mutex

A mutex is a synchronization primitive that allows only one thread or other execution unit at a time to access a protected resource.

28 keywords23 linked from3 not yet writtenWritten by AI
Synchronization…Concurrent compu…Thread (Computin…Mutual exclusionRace conditionCritical sectionPseudocodeCompilerMutex

A mutex, short for mutual exclusion, is a synchronization primitive that gives one execution unit at a time exclusive access to a shared resource. In concurrent computing, a thread typically acquires a mutex before accessing protected data and releases it afterward. If another thread already holds the mutex, acquisition may wait until it becomes available. Mutexes implement mutual exclusion and help prevent race conditions, but their effectiveness depends on all relevant accesses following the same synchronization protocol.

Operation and ownership

A mutex has two basic logical states: unlocked and locked. Its interface normally provides:

  • Lock, or acquire: obtain exclusive ownership, waiting if necessary.
  • Unlock, or release: relinquish ownership so another execution unit can acquire the mutex.
  • Try-lock: attempt acquisition without waiting for the mutex to become available, reporting success or failure.
  • Timed lock, where supported: attempt acquisition subject to a timeout or deadline.

Unlike a plain Boolean flag, a mutex coordinates competing acquisition attempts so that no two threads can successfully become its owner at the same time.

The code executed while holding a mutex is called a critical section. For example, the following pseudocode protects a shared counter:

lock(counter_mutex)
try:
    counter = counter + 1
finally:
    unlock(counter_mutex)

Incrementing a counter can involve separate read, arithmetic, and write operations. Without synchronization, two threads could read the same old value and overwrite each other’s updates. If every concurrent access requiring protection uses the same mutex, the relevant operations are serialized.

A conventional mutex has an owner: the thread that acquired it is responsible for releasing it. Attempting to unlock a mutex from a different thread is invalid in many interfaces, although the precise result depends on the interface and mutex type. Task-oriented asynchronous mutexes may instead associate ownership with a logical task or guard object.

A mutex protects a resource by convention; it does not automatically prevent code from accessing that resource without acquiring the lock.

Correctness and memory visibility

Mutual exclusion is only part of the guarantee required for shared-data synchronization. Modern processors and compilers may reorder operations when permitted by the applicable memory model. Standard mutex interfaces therefore also define memory-ordering effects.

Typically, releasing a mutex publishes preceding changes, and a subsequent successful acquisition of the same mutex by another thread establishes the ordering needed to observe those changes. In language standards that use the term, this contributes to a happens-before relationship.

These guarantees distinguish a mutex from an ordinary flag. A flag implemented without appropriate atomic operations and memory ordering may fail both to exclude competing threads and to make protected writes visible. The volatile qualifier in languages such as C and C++ is not a replacement for mutex synchronization.

Correct locking must protect an entire logical operation, not merely its individual instructions. For example, checking whether a queue is nonempty and then removing an item generally requires one protected operation. Releasing the mutex between the check and removal would allow another thread to change the queue in the meantime.

Mutexes are often used to preserve invariants across a data structure, such as keeping an item count consistent with the contents of a collection. The protected state must satisfy the required invariants whenever ownership passes to another thread.

Implementation

Mutexes may be supplied by an operating system, a runtime, or a programming-language library. Their implementation commonly combines processor-level atomic operations with facilities for suspending and waking waiting threads.

Fast and contended paths

In the uncontended case, a thread can often acquire and release a mutex using a small number of atomic operations without entering the operating-system kernel.

In the contended case, the implementation may:

  1. Retry briefly while checking whether the mutex has become available.
  2. Place the thread in a waiting state.
  3. Arrange for a waiting thread to become runnable after release.

The exact sequence varies. Some implementations spin for a limited period before blocking; others block sooner. This can trade processor time against the overhead of suspending and resuming a thread.

On Linux, a futex provides a mechanism for waiting on and waking threads associated with a value in user memory. Thread libraries can use it to implement mutexes whose uncontended operations remain in user space. A futex is not itself synonymous with a complete mutex: the surrounding library supplies the locking protocol and other semantics.

Scheduling and fairness

Unlocking a mutex does not universally guarantee that the longest-waiting thread acquires it next. Depending on implementation and scheduling, an arriving thread may acquire it before an existing waiter.

Mutual exclusion therefore does not by itself guarantee fairness or freedom from starvation. Strict handoff policies can improve predictability, but may have different performance costs from policies that favor throughput.

Types and interface variations

Mutex semantics differ across libraries and operating systems.

Type or feature Meaning
Nonrecursive mutex Does not permit ordinary repeated acquisition by its current owner; the result of attempting this depends on the interface.
Recursive mutex Allows its owner to acquire it repeatedly, with a matching number of releases required before another thread can acquire it.
Error-checking mutex Detects specified misuse, such as certain ownership errors, and reports an error.
Timed mutex Supports acquisition with a timeout or deadline.
Robust mutex Provides a defined way to detect and handle the termination of an owner while it held the mutex.
Process-shared mutex Can coordinate execution units in different processes when supported and correctly initialized.

These features are not necessarily mutually exclusive.

A recursive mutex can support nested calls that acquire the same lock, but does not make arbitrary reentrant behavior safe. Nested code may still encounter partially updated state.

A robust mutex does not automatically repair protected data. For example, a supporting POSIX interface can report that the previous owner died, after which recovery code must establish whether the protected state can be made consistent.

A mutex used between processes must be designed for that purpose. Merely placing an ordinary thread-local synchronization object in shared memory is not sufficient.

Relationship to other synchronization mechanisms

Semaphores

A semaphore maintains a count and can represent multiple available permits. A binary semaphore can be used in some mutual-exclusion protocols, but it is not generally interchangeable with a mutex.

The central distinction is ownership: a mutex normally must be released by its owner, whereas a semaphore can commonly be signaled by a different thread. Semaphores therefore also support event notification and resource counting.

Spinlocks

A spinlock repeatedly checks for availability instead of putting the waiting thread to sleep. Spinning can be useful for very short waits when the lock holder can run on another processor, but wastes processor time when waits are long or the owner cannot run.

Terminology varies: some systems describe spinlocks as a kind of mutex, while others reserve mutex for a blocking lock. Hybrid mutexes can combine spinning and blocking.

Reader–writer locks

A reader–writer lock permits multiple readers at once, while requiring exclusive access for writers. It can improve concurrency for some read-heavy workloads, but adds bookkeeping and policy questions, including whether readers or writers receive preference. It is not necessarily faster than a mutex.

Condition variables

A condition variable allows a thread to wait until a predicate about shared state may have become true. A condition-variable wait releases the associated mutex and enters the waiting protocol atomically, then reacquires the mutex before returning.

The predicate must be checked in a loop:

lock(queue_mutex)
try:
    while queue is empty:
        wait(queue_changed, queue_mutex)
    item = remove_first(queue)
finally:
    unlock(queue_mutex)

Rechecking is necessary because wakeups may be spurious, or another thread may change the state before the awakened thread reacquires the mutex.

Failure modes and limitations

Deadlock

A deadlock can occur when threads wait indefinitely for locks held by one another. For example, one thread may hold mutex A while waiting for B, while another holds B while waiting for A.

Consistent lock ordering can prevent this particular circular-wait pattern. Reacquiring a nonrecursive mutex already held by the same thread can also cause self-deadlock, depending on the mutex interface. Recursive mutexes address that specific situation, not deadlocks involving multiple resources.

Priority inversion

Priority inversion occurs when a high-priority thread waits for a mutex held by a lower-priority thread, while other runnable work delays the owner. Priority inheritance can temporarily raise the owner’s effective priority; priority-ceiling protocols provide another approach under specified scheduling assumptions. Such features matter particularly in a real-time operating system, but are not universal mutex properties.

Contention and scalability

A heavily contended mutex becomes a serialization point. Adding threads may then increase waiting rather than useful parallelism. Transferring lock ownership and protected data among processors can also generate cache traffic.

Coarse-grained locking uses fewer mutexes to protect larger amounts of state, simplifying reasoning but reducing concurrency. Fine-grained locking can allow more independent work, at the cost of more complex ownership rules and greater risk of lock-order errors.

Lifetime and abnormal execution

A mutex must remain valid while threads may own it or attempt to use it. Destroying a locked mutex or freeing its storage while it is still accessible violates typical interface requirements.

Exceptions, early returns, cancellation, or owner termination can leave a mutex locked unless release is guaranteed by the surrounding mechanism. Scoped guards, context managers, and structured cleanup connect release to the lifetime of a protected scope. Blocking operations and callbacks executed while holding a mutex can also extend lock duration or introduce unexpected dependencies.

Use in asynchronous and distributed systems

In asynchronous programming, a blocking mutex may block an entire execution thread, including an event loop that needs to run other tasks. An asynchronous mutex instead suspends the waiting task while allowing the executor to run other work. Holding a lock across a suspension point can still create contention or deadlock, depending on the program’s dependencies.

A local mutex does not automatically provide mutual exclusion across machines. Distributed systems require protocols that account for communication failure, process failure, and uncertain timing. Lease expiration, for example, may allow a new owner to proceed while an old owner is still running; local mutex ownership rules alone do not address that situation.