π Mutex Locks in Process Synchronization (36 MCQs)
Mutual Exclusion Locks and Protected Critical Sections
A mutex lock is a synchronization primitive that allows only one participating thread or process to access a protected resource at a time. The lock has an available state and an acquired state, with operations commonly called acquire and release. Mutexes are widely used in operating systems, libraries, and applications to protect shared variables, data structures, and kernel resources.
Why Shared Data Requires Exclusive Ownership
Concurrent threads may access and modify the same memory location, producing inconsistent results when updates overlap. A mutex establishes an ownership rule so that one thread performs the protected operation while others wait. This prevents conflicting updates, although the application must ensure that every relevant access follows the same locking protocol.
Acquire, Critical-Section Execution, and Release
A thread invokes the lock operation before accessing protected data. If the mutex is available, the thread acquires ownership and enters its critical section. Otherwise, it waits or spins according to the implementation. After completing the protected operation, the owning thread releases the mutex, allowing another eligible thread to acquire it.
Preventing Concurrent Updates to a Shared Counter
Suppose a shared counter begins at zero and two threads each perform 1,000 increments. Both acquire the same mutex before updating the counter and release it afterward. The protected increments prevent lost updates, producing a final value of 2,000. Without the mutex, overlapping read-modify-write operations could produce a smaller result.
Lock Contention, Blocking, and Ownership Costs
Mutexes provide straightforward protection for shared data in databases, file systems, and multithreaded applications. Blocking mutexes avoid wasting CPU time during long waits, whereas spin-based implementations suit some short critical sections. However, contention increases latency, excessive locking reduces parallelism, and incorrect lock ordering can produce deadlock or priority inversion.
Misconceptions About Mutex Ownership and Behaviour
'A mutex can be released safely by any thread' is incorrect because ownership rules generally restrict release to its owner. 'A mutex always causes busy waiting' is incorrect because implementations can block waiting threads. 'Using one mutex guarantees the whole program is race-free' is incorrect because unprotected shared accesses may remain.
Exam Focus: Mutex Acquisition and Critical-Section Traces
Trace lock acquisition and release among competing threads and identify which thread owns the mutex at each stage. Distinguish blocking mutexes from spinlocks and explain how mutual exclusion prevents lost updates. Questions may examine lock contention, ownership rules, nested locking, deadlocks, and the importance of releasing locks on every appropriate execution path.
Key Terms of Mutex Synchronization
- Mutex - Lock providing exclusive access.
- Acquire - Operation obtaining lock ownership.
- Release - Operation making the lock available.
- Contention - Competition for an unavailable lock.
- Owner - Thread currently holding the mutex.
- Deadlock - Circular waiting preventing progress.
π All Mutex Locks in Process Synchronization MCQs
Q1. A banking service checks whether an account has enough funds and then subtracts a withdrawal. Why should both steps use the same mutex-protected region?
π Explanation: The check and subtraction form one logical operation. Without one protected region, another thread can change the balance after the check, making the earlier decision invalid even when individual memory accesses are atomic.
Q2. Two worker threads each increment a shared counter 500 times. Every increment is performed while holding the same correctly initialized mutex. What final value is guaranteed when the counter starts at zero?
π Explanation: The mutex serializes the read-modify-write increments, so no update is overwritten. Both workers complete 500 increments, giving a total of 500 + 500 = 1,000 in total regardless of their execution order.
Q3. A shared stock record is read, checked for sufficient quantity, and then reduced. Which design best preserves the stock invariant when several checkout threads run concurrently?
π Explanation: The quantity can change between separate protected steps. Keeping the check and decrement under one mutex makes the decision and state change indivisible relative to other checkout threads, preserving the stock constraint.
Q4. A student says, A mutex is unnecessary because reading and writing a machine-word integer are individually atomic. The code still reads the value, checks a condition, and then writes a new value. What is the flaw?
π Explanation: The flawed reasoning treats separate atomic accesses as one indivisible operation. Another thread can modify the value between the read and write, so the compound invariant still needs a mutex or a suitable atomic retry algorithm.
Q5. A thread must update a shared queue. Which sequence correctly uses a mutex to protect the update?
π Explanation: The thread must obtain exclusive ownership before touching the protected queue. It performs the update while holding the lock and releases it afterward, allowing another eligible thread to enter safely.
Q6. A proposed mutex uses this sequence: read available; if true, write false. Two processors can execute these steps simultaneously. What can happen?
π Explanation: The test and state change are separate operations, so both processors may read the available value before either writes false. Acquisition must be atomic, usually through a hardware-supported read-modify-write operation.
Q7. A mutex API specifies that only its current owner may unlock it. Thread R tries to unlock a mutex owned by thread S. How should this action be classified?
π Explanation: Mutex ownership associates the right to release the lock with the thread that acquired it. A different thread cannot safely pretend to release that ownership; the API may report an error or define the behavior as invalid.
Q8. A file-processing thread acquires a mutex, then encounters an error before reaching the ordinary unlock statement. What coding practice most directly prevents the lock from remaining held?
π Explanation: Every control-flow path after successful acquisition must release the mutex. A cleanup construct such as a finally block or scoped guard ensures that errors and early returns do not leave the shared resource permanently locked.
Q9. Thread T owns a non-recursive mutex and calls a helper that attempts to acquire that same mutex. The helper blocks until acquisition succeeds. What is the likely outcome?
π Explanation: A non-recursive mutex does not permit its owner to acquire it again before unlocking. Because the helper blocks and the caller cannot continue to release the lock, the thread can deadlock itself.
Q10. A parent thread locks mutex M, starts a child, and waits for the child to finish. The child must acquire M before it can finish. Why can this program hang?
π Explanation: The parent cannot finish waiting until the child completes, while the child cannot complete until M is released. Since the parent retains M during the wait, the dependency prevents either thread from progressing.
Q11. A component calls an external callback while holding mutex M. The callback may call back into the component and attempt to acquire M. Which risk should the designer address?
π Explanation: Calling unknown code while holding a lock exposes the component to reentrant calls and hidden lock dependencies. The callback may try to acquire M again or acquire another lock in an incompatible order.
Q12. A thread calls try_lock on a mutex and the operation reports failure immediately. What is the correct interpretation?
π Explanation: A failed try_lock reports that ownership was not obtained at that moment. It does not prove deadlock or destroy the mutex; the caller must follow a retry, fallback, or error-handling path.
Q13. A lock implementation repeatedly checks whether a mutex is free instead of putting the waiting thread to sleep. What is this waiting strategy called?
π Explanation: Repeatedly testing the lock while remaining runnable is busy waiting. A mutex implemented this way is commonly called a spinlock, because the waiting thread consumes processor cycles while checking for release.
Q14. A multiprocessor kernel protects a very short critical section. The lock owner is running on one CPU, while another CPU waits. Why might a spinlock be reasonable?
π Explanation: When the critical section is extremely short and the owner can continue running, a waiter may acquire the lock quickly. Avoiding sleep and wakeup scheduling costs can outweigh the brief processor time spent spinning.
Q15. A database operation holds a mutex while performing a disk read that may take 80 milliseconds. Other threads need the same mutex. Which waiting approach is generally preferable for those contenders?
π Explanation: An 80-millisecond wait is long relative to ordinary scheduling costs. Blocking lets the processor run useful work instead of repeatedly checking the lock, whereas spinning would waste substantial CPU time.
Q16. A benchmark reports these pairs of owner hold time and waiting-thread CPU time: (1 ms, 0.8 ms); (2 ms, 1.8 ms); (3 ms, 2.9 ms); (4 ms, 3.9 ms); (5 ms, 4.9 ms). Which conclusion best fits the data for a spin-based lock?
π Explanation: The waiting thread continues consuming a processor while the owner holds the lock. The paired measurements rise almost one-for-one, showing that longer ownership periods create correspondingly greater wasted spinning time.
Q17. A web service acquires mutex M before sending a request to a remote server, then keeps M until the response arrives. Unrelated cache updates also require M. What is the best improvement when the data invariant permits it?
π Explanation: Network delays can be unpredictable and much longer than a local update. Moving the remote wait outside the critical section shortens lock ownership, reducing contention while preserving protection around the actual shared-state changes.
Q18. A report function needs a consistent snapshot of a shared counter but then spends several seconds formatting output. Which design usually reduces contention without changing the snapshot?
π Explanation: The function needs protection only while copying the shared value consistently. Once it has a local snapshot, formatting can proceed without holding the mutex, allowing other threads to update the counter sooner.
Q19. A load test records worker count and mean mutex wait in milliseconds: (1, 0.0); (2, 0.2); (4, 0.6); (8, 1.9); (12, 3.8); (16, 6.4). Which interpretation is most strongly supported?
π Explanation: The measured wait increases sharply as the number of contenders rises. Since a mutex grants only one owner at a time, the pattern is consistent with growing lock contention and serialized access to the protected resource.
Q20. A telemetry application updates two independent counters. Profiling shows unnecessary waiting because both counters use one mutex. Which redesign can safely improve parallelism?
π Explanation: Separate locks let threads update unrelated counters concurrently. This is safe only when no operation must preserve a relationship across both values; such joint operations still need coordinated protection of the shared invariant.
Q21. A service uses one mutex for each field of a record. A transaction must update both fields so that their sum always equals 100. What must the transaction do?
π Explanation: Separate locks protect individual fields but do not automatically preserve a relationship between them. The joint update must coordinate both fields, using a consistent acquisition order or another mechanism that makes the combined change indivisible.
Q22. A system measures mutex hold time and completed operations per second: (0.5 ms, 920); (1 ms, 760); (2 ms, 510); (3 ms, 340); (4 ms, 230); (5 ms, 170). What is the strongest conclusion?
π Explanation: As hold time increases, fewer operations complete per second. The mutex serializes access, so lengthening the protected interval reduces opportunities for other workers to proceed; the data does not identify every source of work.
Q23. Thread A updates shared structure X and then unlocks mutex M. Thread B later successfully locks the same M before reading X. What should a correctly implemented mutex provide?
π Explanation: A mutex with proper acquire and release memory-ordering semantics makes the ownerβs earlier protected writes visible to a later successful acquirer. This guarantee applies to the synchronization relationship, not arbitrary unrelated accesses.
Q24. Thread A increments a shared value while holding mutex M. Thread B increments the same value using an atomic instruction but does not acquire M. Why can the design still be incorrect?
π Explanation: The atomic operation does not acquire M or participate in its ownership protocol. Mixing it with other protected operations can break compound invariants and, for non-atomic accesses to the same object, may create a data race.
Q25. A program publishes a mutex pointer to worker threads before the mutex has been initialized. What is the main concern?
π Explanation: A mutex must be fully initialized before any thread uses it. Publishing the pointer too early creates a race between initialization and acquisition, so workers may invoke operations on an invalid synchronization object.
Q26. A function locks a mutex, obtains a pointer to an element in a shared list, unlocks, and then reads through the pointer. Another thread may remove and free that element. What is the central risk?
π Explanation: The mutex protects the pointer lookup only while held. After unlock, another thread can remove or free the node, so later dereferencing may access invalid memory; object lifetime needs separate protection.
Q27. Thread A acquires M then requests N. Thread B acquires N then requests M. Both locks are non-recursive and neither thread releases its first lock while waiting. What can occur?
π Explanation: A holds M while waiting for N, and B holds N while waiting for M. Neither can reach its release operation, forming a circular wait that can deadlock both threads.
Q28. A codebase has many paths that acquire mutexes M and N. Which policy most directly prevents the common two-lock circular-wait pattern?
π Explanation: A global acquisition order prevents one path from holding M while waiting for N as another holds N while waiting for M. Every code path must follow the same order whenever both locks are required.
Q29. Two threads always acquire mutexes M then N. One releases M before N, while the other releases N before M. Does the differing release order alone establish a deadlock?
π Explanation: Deadlock commonly arises from incompatible acquisition orders that create circular wait. Different release orders alone do not prove deadlock, but each thread must still release only locks it owns and preserve shared-state consistency.
Q30. A thread holds mutex M while waiting for another thread to terminate. The terminating thread needs M to perform cleanup before exiting. Which change most directly breaks this dependency?
π Explanation: The waiting thread blocks the cleanup operation by retaining the mutex that the terminating thread needs. Releasing it before waiting, when invariants permit, removes that dependency and allows termination to complete.
Q31. A thread waits for a condition using a condition-variable operation associated with mutex M. The operation atomically releases M while sleeping and reacquires it before returning. Why is that useful?
π Explanation: Releasing M during the wait allows another thread to enter the protected region and update the predicate. Reacquiring M before return restores synchronized access so the waiter can safely inspect shared state.
Q32. A worker wakes after waiting for a condition that a shared queue is nonempty. Before it reacquires the mutex, another worker may remove the last item. What should the awakened worker do?
π Explanation: A wakeup indicates that the condition may have changed, not that it must still be true. The worker should reacquire the mutex and recheck the predicate in a loop before consuming the shared queue.
Q33. A low-priority thread owns mutex M. A high-priority thread blocks on M, while medium-priority threads repeatedly preempt the owner. Which issue can result?
π Explanation: The high-priority thread is indirectly delayed because medium-priority work prevents the low-priority owner from running and releasing M. Priority inheritance can temporarily raise the ownerβs priority to reduce this inversion.
Q34. A developer claims that adding a mutex around one shared object guarantees that the entire application cannot deadlock. Which counterexample best disproves the claim?
π Explanation: A mutex prevents simultaneous ownership of that particular lock, but it does not prevent circular waits across multiple locks. Opposite acquisition orders can deadlock even when each mutex works correctly.
Q35. A shared state transition reads one integer, calculates a replacement, and writes it back. Under which condition could a compare-and-swap loop reasonably replace the mutex?
π Explanation: A compare-and-swap loop can implement a simple atomic state transition when interference causes a retry and recomputation is safe. It is unsuitable when retries repeat irreversible effects or when a wider multi-object invariant must be preserved.
Q36. A performance test reports worker count and average mutex wait time: (2, 0.1 ms); (4, 0.3 ms); (8, 0.9 ms); (12, 2.1 ms); (16, 4.7 ms); (20, 7.5 ms). Which additional measurement would best confirm whether contention is the bottleneck?
π Explanation: Rising wait time suggests contention, but profiling lock hold durations and total time blocked provides stronger evidence. These measurements distinguish serialization at the mutex from delays caused by unrelated computation or I/O.