‹ All Operating Systems questions

Operating Systems Practice Question 6: Lock Ordering Deadlock

Operating Systems · Test 1 · question 6 of 10

Deadlockmedium

A banking service transfers money between two accounts. transfer(from, to) locks from's mutex, then to's mutex, moves the money, and unlocks both. Occasionally the service hangs forever: one thread is running transfer(A, B) while another runs transfer(B, A).

Which change removes the deadlock while still letting transfers on unrelated accounts run in parallel?

Select one answer
Show answer and explanation

Answer:

  • B. Always acquire the two account locks in a fixed global order, such as by account ID

Deadlock needs all four Coffman conditions: mutual exclusion, hold-and-wait, no preemption, and circular wait. Here thread 1 holds A and waits for B while thread 2 holds B and waits for A, a cycle. Removing any one condition prevents deadlock, and the most practical is circular wait: impose a total order on lock acquisition. If every transfer locks the lower-numbered account first, both threads try A first, one waits, and no cycle can form. Transfers between different accounts still use different locks and run in parallel.

Option A would prevent the deadlock (it removes hold-and-wait: there is only one lock to hold), but it serialises every transfer in the system, which the stem rules out.

Option C is wrong: priority changes which thread runs first, not the lock order. If the higher-priority thread is interrupted after its first lock, or the threads run on separate cores, the cycle can still form.

Option D is wrong: a sleep only changes timing. It actually widens the window in which both threads hold their first lock, making the deadlock *more* likely, not impossible.

Reference: OSTEP - Common Concurrency Problems

Practice Test 1 ›