linux-sysprog · intermediate · ~15 min
Detect the classic lock-ordering deadlock.
The classic deadlock: two threads grab the same two locks in opposite order, so each ends up holding the lock the other needs next — a circular wait. Detect that AB-BA pattern.
Implement int deadlock_risk(int t1_first, int t1_second, int t2_first, int t2_second) that returns 1 if thread 1 takes locks (A, B) while thread 2 takes (B, A) with A and B distinct, else 0.
t1_first, t1_second: lock ids thread 1 acquires, in order.t2_first, t2_second: lock ids thread 2 acquires, in order.1 if t1_first != t1_second, t1_first == t2_second, and t1_second == t2_first; else 0.
deadlock_risk(1, 2, 2, 1) -> 1 (AB vs BA)
deadlock_risk(1, 2, 1, 2) -> 0 (same order, safe)
deadlock_risk(1, 2, 3, 4) -> 0 (disjoint locks)
t1_first/t1_second: thread 1's lock order; t2_first/t2_second: thread 2's.
1 if the two distinct locks are taken in opposite order, else 0.
The pair must be distinct locks acquired AB by one and BA by the other.
int deadlock_risk(int t1_first, int t1_second, int t2_first, int t2_second) {
/* TODO */
return 0;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.