Search code examples
operating-systemdeadlock

What is the logic behind this deadlock problem answer?


I must solve this problem:

Two processes, A and B, each need three records, 1, 2, and 3, in a database. If A asks for them in the order 1, 2, 3, and B asks for them in the same order, deadlock is not possible. However, if B asks for them in the order 3, 2, 1, then deadlock is possible. With three resources, there are 3! or six possible combinations in which each process can request them. What fraction of all the combinations is guaranteed to be deadlock free?

And I've seen the solution to this problem in a book:

123 deadlock free
132 deadlock free
213 possible deadlock
231 possible deadlock
312 possible deadlock
321 possible deadlock

Since four of the six may lead to deadlock, there is a 1/3 chance of avoiding a deadlock and a 2/3 chance of getting one.

But I can't figure out what logic is behind of this solution.
Would someone please explain why this solution is correct?
I've searched a lot but didn't find anything and all of the answers to this problem was without clear explanation.


Solution

  • Deadlock occurs when both threads must wait to acquire a lock that the other thread already acquired (causing both threads to wait forever).

    If both threads try to acquire the same lock first then only one thread can succeed and the other must wait, and the waiting thread will be waiting while not holding any locks, so deadlock can't happen because the thread that acquired lock 1 will be able to acquire all other locks it wants and will be able to release lock 1 when its finished (which allows the waiting thread to continue).

    E.g. if A and B try to acquire lock 1 first and A wins, then B waits while not holding any lock and A can acquire any other locks in any order it wants because B isn't holding any locks (and then A will release lock 1 and B can stop waiting).