I've been working on some examples of the Lock tree deadlock detection algorithm and been unable to figure out how a deadlock occurs in this particular situation:
Thread 1: Thread 2:
lock(A) lock(E)
lock(C) lock(D)
unlock(C) unlock(D)
lock(B) unlock(A)
lock(D) lock(A)
lock(E) lock(C)
unlock(E) unlock(C)
unlock(D) unlock(A)
unlock(B)
unlock(A)
From my understanding the Lock tree should look something like this:
T1: T2:
/ \
A E A
/ \ | |
C B D C
|
D
|
E
Could it be that the deadlock occurs at nodes T1: D - E and T2: E - D, because the threads take those locks in opposite order?
How could I suggest insertion of one lock and one unlock statement to remove the deadlock?
thread 1 does: lock(a), lock(c),unlock(c),lock(b),lock(d)
so now a,b and d are locked
thread 2 does: lock(e), lock(d)
so now e is locked as well and thread 2 is waiting for d to unlock
now thread one wakes up and does: lock(e)
now they are stuck -
1 is waiting for 2 to unlock e.
2 is waiting for 1 to unlock d
one of the methods to avoid this is to lock everything you need at once, and not as separate operations.