πŸŽ“ BookMCQ
← Back to 5. Process Synchronization

πŸ“ 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.
12
Easy
12
Medium
12
Hard

πŸ“ 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?

A.The mutex makes subtraction execute in fewer instructions
B.It prevents another withdrawal from changing the balance between the check and subtraction βœ…
C.It automatically reverses withdrawals that create a negative balance
D.It makes every integer read indivisible without any other guarantee
πŸ’‘ Difficulty: easy | βœ… Correct: B

πŸ“– 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?

A.500
B.750
C.999
D.1000 βœ…
πŸ’‘ Difficulty: easy | βœ… Correct: D

πŸ“– 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?

A.Lock only the final subtraction
B.Use separate mutexes for the check and the update without coordination
C.Allow each thread to check under the lock but update after unlocking
D.Use a mutex around the complete check-and-update sequence βœ…
πŸ’‘ Difficulty: medium | βœ… Correct: D

πŸ“– 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?

A.Atomic reads and writes do not make the entire read-check-write sequence atomic βœ…
B.Machine-word integers cannot be shared between threads
C.A mutex is required only when the variable contains a pointer
D.The condition check automatically prevents another thread from running
πŸ’‘ Difficulty: easy | βœ… Correct: A

πŸ“– 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?

A.Update the queue, acquire the mutex, then release it
B.Update the queue while another thread owns the mutex
C.Acquire the mutex, release it, then update the queue
D.Acquire the mutex, update the queue, then release the mutex βœ…
πŸ’‘ Difficulty: easy | βœ… Correct: D

πŸ“– 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?

A.Both processors can observe true and both believe they acquired the lock βœ…
B.Only the processor with the larger identifier can acquire it
C.The available flag becomes permanently true
D.The processors automatically combine their writes into one acquisition
πŸ’‘ Difficulty: hard | βœ… Correct: A

πŸ“– 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?

A.A normal way to transfer ownership
B.A safe way to wake all waiting threads
C.Equivalent to S releasing the mutex
D.An ownership violation and a programming error βœ…
πŸ’‘ Difficulty: medium | βœ… Correct: D

πŸ“– 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?

A.Retry the file operation forever while holding the mutex
B.Use a guaranteed cleanup path, such as a finally block or scoped lock guard βœ…
C.Let another thread unlock the mutex after a delay
D.Delete the shared file before returning
πŸ’‘ Difficulty: easy | βœ… Correct: B

πŸ“– 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?

A.The mutex recognizes the owner and increments a recursion count
B.The helper releases the mutex on behalf of T
C.T may block waiting for a lock that it cannot release while blocked βœ…
D.The operating system silently creates a second copy of the mutex
πŸ’‘ Difficulty: medium | βœ… Correct: C

πŸ“– 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?

A.The child has a higher thread identifier
B.The child must acquire every mutex twice
C.Starting a child always releases all mutexes
D.The parent waits while holding the lock that the child needs to complete βœ…
πŸ’‘ Difficulty: hard | βœ… Correct: D

πŸ“– 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?

A.The callback will automatically inherit ownership of M
B.The mutex becomes a counting semaphore
C.The callback may cause self-deadlock or an unexpected lock-order cycle βœ…
D.The operating system must execute the callback on another processor
πŸ’‘ Difficulty: hard | βœ… Correct: C

πŸ“– 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?

A.The thread now owns the mutex but must wait to use it
B.The mutex has been destroyed
C.The current owner has necessarily deadlocked
D.The lock was not acquired, so the thread must not access the protected data as its owner βœ…
πŸ’‘ Difficulty: easy | βœ… Correct: D

πŸ“– 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?

A.Busy waiting βœ…
B.Priority inheritance
C.Lock elision
D.Condition signaling
πŸ’‘ Difficulty: easy | βœ… Correct: A

πŸ“– 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?

A.Spinning always consumes less energy than blocking
B.The expected wait may be shorter than the cost of blocking and waking the waiter βœ…
C.A spinlock guarantees FIFO acquisition
D.A spinlock allows several owners into the critical section
πŸ’‘ Difficulty: medium | βœ… Correct: B

πŸ“– 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?

A.Spin continuously for the entire disk-read interval
B.Disable processor interrupts until the read completes
C.Use a blocking wait so a contender can be descheduled while the owner performs the long operation βœ…
D.Let all contenders enter the critical section during the read
πŸ’‘ Difficulty: hard | βœ… Correct: C

πŸ“– 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?

A.Waiting CPU time stays nearly constant as hold time rises
B.Waiting CPU time grows roughly with the time spent holding the lock βœ…
C.The lock becomes non-exclusive after 3 ms
D.The owner hold time is determined by the waiting thread
πŸ’‘ Difficulty: medium | βœ… Correct: B

πŸ“– 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?

A.Move the remote wait outside the locked region and keep only necessary shared-state operations protected βœ…
B.Increase the number of threads waiting on M
C.Keep M locked and poll the remote server more frequently
D.Allow cache updates to bypass M
πŸ’‘ Difficulty: medium | βœ… Correct: A

πŸ“– 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?

A.Hold the mutex throughout formatting and printing
B.Read the counter without locking because it is only one integer
C.Copy the counter while holding the mutex, unlock, and format the local copy βœ…
D.Ask every worker to stop permanently before printing
πŸ’‘ Difficulty: easy | βœ… Correct: C

πŸ“– 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?

A.More workers eliminate serialization at the mutex
B.Wait time grows as more workers compete for the same exclusive lock βœ…
C.The protected operation must become shorter as worker count rises
D.The mutex is granting simultaneous ownership to all workers
πŸ’‘ Difficulty: hard | βœ… Correct: B

πŸ“– 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?

A.Remove all locks even though both counters remain shared
B.Use one recursive mutex for both counters
C.Use a separate mutex for each counter if no invariant requires a joint update βœ…
D.Protect both counters with a mutex that is never released
πŸ’‘ Difficulty: medium | βœ… Correct: C

πŸ“– 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?

A.Acquire suitable coordination for both fields during the joint update βœ…
B.Lock only the field that is written last
C.Update each field under its own lock at unrelated times
D.Read both fields without locks because each field has a mutex
πŸ’‘ Difficulty: hard | βœ… Correct: A

πŸ“– 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?

A.Longer critical sections are associated with lower throughput in this workload βœ…
B.Throughput rises whenever the lock is held longer
C.The mutex permits more concurrent owners at 5 ms
D.The measurements prove that all computation occurs inside the mutex
πŸ’‘ Difficulty: hard | βœ… Correct: A

πŸ“– 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?

A.No visibility relationship, because unlocking only changes a Boolean
B.Visibility only if both threads run on the same processor
C.The writes made before A unlocks are visible to B after its successful acquisition βœ…
D.A guarantee that B reads every unrelated variable in the entire program
πŸ’‘ Difficulty: medium | βœ… Correct: C

πŸ“– 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?

A.The atomic increment automatically joins M ownership
B.The two update protocols are not mutually coordinated, so a larger invariant or mixed access pattern may still be violated βœ…
C.An atomic instruction always resets the mutex to available
D.The mutex prevents every atomic instruction from executing
πŸ’‘ Difficulty: hard | βœ… Correct: B

πŸ“– 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?

A.Workers may operate on an uninitialized synchronization object, producing invalid or undefined behavior βœ…
B.The mutex will necessarily become recursive
C.Every worker will receive ownership automatically
D.Initialization will be completed atomically by the first unlock
πŸ’‘ Difficulty: easy | βœ… Correct: A

πŸ“– 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?

A.The pointer is automatically refreshed when the mutex is unlocked
B.A mutex can protect list nodes only during insertion
C.The list becomes immutable after the first unlock
D.The pointed-to object may be freed or changed after the protection ends βœ…
πŸ’‘ Difficulty: hard | βœ… Correct: D

πŸ“– 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?

A.Both threads enter both critical sections simultaneously
B.A circular wait in which each thread holds one mutex and waits for the other βœ…
C.The mutexes automatically change their acquisition order
D.The operating system merges M and N into one lock
πŸ’‘ Difficulty: hard | βœ… Correct: B

πŸ“– 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?

A.Release whichever mutex was acquired first
B.Allow each function to choose its own order
C.Require every path to acquire M before N βœ…
D.Use a longer critical section for the second mutex
πŸ’‘ Difficulty: medium | βœ… Correct: C

πŸ“– 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?

A.Yes, any difference in release order necessarily creates circular wait
B.No; deadlock risk mainly depends on acquisition dependencies, though every unlock must still obey ownership and program invariants βœ…
C.Yes, because mutexes must be released alphabetically
D.No; release operations can be performed by any thread
πŸ’‘ Difficulty: easy | βœ… Correct: B

πŸ“– 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?

A.Make the terminating thread wait for the first thread
B.Acquire M again immediately before waiting
C.Increase the join timeout but keep M locked indefinitely
D.Release M before waiting when safe, or redesign cleanup so the other thread does not need M βœ…
πŸ’‘ Difficulty: hard | βœ… Correct: D

πŸ“– 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?

A.It lets another thread acquire M and change the condition while the waiter sleeps βœ…
B.It permanently transfers M ownership to the signaling thread
C.It guarantees the condition remains true after wakeup
D.It removes the need to protect the condition predicate
πŸ’‘ Difficulty: medium | βœ… Correct: A

πŸ“– 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?

A.Assume the queue is nonempty because it was signaled
B.Read the queue without locking to avoid another wait
C.Recheck the predicate in a loop while holding the mutex βœ…
D.Unlock the mutex and process an item that may no longer exist
πŸ’‘ Difficulty: easy | βœ… Correct: C

πŸ“– 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?

A.The high-priority thread takes ownership without acquiring M
B.Priority inversion, which priority inheritance can help mitigate βœ…
C.A guaranteed FIFO transfer of the mutex
D.The medium-priority threads become mutex owners automatically
πŸ’‘ Difficulty: medium | βœ… Correct: B

πŸ“– 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?

A.One thread acquires and releases the same mutex normally
B.A thread reads a private local variable
C.Two threads acquire two different mutexes in opposite orders and wait for one another βœ…
D.A mutex is initialized before worker threads start
πŸ’‘ Difficulty: easy | βœ… Correct: C

πŸ“– 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?

A.The transition is retryable, and failed attempts can recompute the new value without irreversible side effects βœ…
B.The operation performs blocking network I/O before every write
C.The update depends on several unrelated objects that must change together
D.The programmer assumes every compare-and-swap attempt succeeds
πŸ’‘ Difficulty: hard | βœ… Correct: A

πŸ“– 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?

A.The number of comments in the source files
B.The executable file size
C.The number of local variables used by each worker
D.Lock hold-time distribution and the fraction of total execution time spent waiting to acquire the mutex βœ…
πŸ’‘ Difficulty: medium | βœ… Correct: D

πŸ“– 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.

πŸ”— Related Topics (MCQs)