Mutex
Subject: Computer and Technology noun /ˈmjuː.tɛks/ 1 definition
- concurrent-computing
- operating-systems
- systems-programming
- thread-synchronization
-
Definition (noun)
Entry #37 · UpdatedA Mutex (short for mutual exclusion) is a synchronization primitive that prevents race conditions by ensuring only one thread or process can access a shared resource or execute a critical section at a time. Before reading or modifying protected state—such as an in-memory data structure, shared buffer, or hardware device—an execution stream must acquire the mutex, forcing competing callers to wait until the current holder releases it. Unlike a counting semaphore that tracks available resource units and can be signaled by any thread, a mutex enforces strict lock ownership so that only the acquiring task is permitted to unlock it.
Common Types
Standard (Non-Recursive) Mutex: Grants exclusive ownership to one thread at a time without tracking nested acquisitions, causing a thread that attempts to re-lock a mutex it already holds to deadlock or return an error.
Recursive (Reentrant) Mutex: Maintains an ownership reference count so the holding thread can safely acquire the same lock multiple times—such as in recursive call chains—and releases ownership only after an equal number of unlock calls.
Read-Write (Shared-Exclusive) Mutex: Separates shared read access from exclusive write access, allowing multiple reader threads to proceed concurrently while blocking writers until all active readers release the lock.
Adaptive (Hybrid) Mutex: Spins briefly on an atomic memory flag when contention is short to avoid kernel context switches, then suspends the waiting thread in the operating system scheduler (such as via a Linux
futex) if the lock remains held.
Example
In a multithreaded C++ order-processing service, two worker threads simultaneously attempt to decrement the same in-memory SKU inventory counter from 10 units as checkout requests arrive. Wrapping the read-modify-write sequence in a
std::mutexlock ensures the first thread finishes updating the count to 9 before the second thread enters the critical section to decrement it to 8, preventing a lost-update race condition.