Mutex locks
acquire/release and spinlocks, interactively.
Operating Systems: Mutex Locks
1. What is a Mutex Lock?
A Mutex Lock (short for Mutual Exclusion Lock) is the simplest software tool provided by operating systems to solve the Critical-Section Problem. It acts as a binary gatekeeper to protect shared variables, memory, or devices from concurrent access.
A mutex uses a boolean variable available whose value indicates if the lock is free (true) or held (false). It defines two main atomic functions:
// Atomic implementation of acquire() void acquire() { while (!available) ; // busy wait (spinlock) available = false; } // Atomic implementation of release() void release() { available = true; }
Key Operational Rules:
- Strict Atomic Calls: Calls to
acquire()andrelease()must complete atomically without hardware interrupts (implemented via atomic instructions likecompare_and_swap). - Ownership Requirement: Only the thread/process that successfully acquired the lock is allowed to release it.
- Binary States: The lock exists in only two states: Unlocked (1/true) or Locked (0/false).
2. Structure of Process using Mutex Lock
Every participating process Pi acquires the lock in its entry section before making modifications in its critical section, releasing it in the exit section:
do { acquire(lock); // Entry Section: Claim lock or wait /* CRITICAL SECTION (Modify shared memory / data) */ release(lock); // Exit Section: Release lock for others /* REMAINDER SECTION */ } while (true);
3. Spinlocks & Trade-Off Analysis
Because the process loops continuously while waiting in acquire(), this type of mutex is known as a Spinlock.
Busy waiting wastes processor execution cycles that other active processes could use productively while a process waits for a lock.
No context switch is required when a process waits on a spinlock. Context switches are expensive CPU operations.
Spinlocks are preferred on multi-core systems when locks are expected to be held for short durations.
4. Interactive Mutex Lock Simulator
Simulate 3 concurrent threads (T0, T1, T2) competing to acquire a shared Mutex Lock.