/ˈmjuːtɛks/
noun — "locks a resource to one thread at a time."
Mutex, short for mutual exclusion, is a synchronization primitive used in multithreaded or multiprocess systems to control access to shared resources. It ensures that only one thread or process can access a critical section or resource at a time, preventing race conditions, data corruption, or inconsistent state. When a thread locks a mutex, other threads attempting to acquire the same mutex are blocked until it is released.
Technically, a mutex maintains an internal flag indicating whether it is locked or unlocked and often a queue of waiting threads. When a thread requests a mutex:
if mutex is unlocked:
lock mutex
else:
block thread until mutex is released
Mutexes may support recursive locking, priority inheritance, or timeout mechanisms to avoid deadlocks and priority inversion. In systems programming, they are commonly used for protecting shared memory, coordinating file access, or managing hardware resources in concurrent environments.
Operationally, using a mutex requires careful discipline. Threads must always release the mutex after completing their critical section, and nested or multiple mutex acquisitions must be managed to prevent deadlocks. High-level abstractions, such as semaphores or monitors, may build on mutexes to provide more complex synchronization patterns.
Example in Python using threading:
import threading
mutex = threading.Lock()
def critical_task():
with mutex: # automatically acquires and releases
# perform actions on shared resource
print("Thread-safe operation")
t1 = threading.Thread(target=critical_task)
t2 = threading.Thread(target=critical_task)
t1.start()
t2.start()
t1.join()
t2.join()
Conceptually, a mutex is like a key to a single-occupancy room: only one person may enter at a time, and others must wait until the key is returned. This guarantees orderly and conflict-free access to limited resources.
See Thread, Process, Deadlock, Synchronization.