linux-sysprog · intermediate · ~15 min

Opposite lock ordering

Detect the classic lock-ordering deadlock.

Challenge

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.

Task

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.

Input

  • t1_first, t1_second: lock ids thread 1 acquires, in order.
  • t2_first, t2_second: lock ids thread 2 acquires, in order.

Output

1 if t1_first != t1_second, t1_first == t2_second, and t1_second == t2_first; else 0.

Example

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)

Edge cases

  • Both threads use the same order: no risk (0).
  • The two locks within a thread must be distinct.

Input format

t1_first/t1_second: thread 1's lock order; t2_first/t2_second: thread 2's.

Output format

1 if the two distinct locks are taken in opposite order, else 0.

Constraints

The pair must be distinct locks acquired AB by one and BA by the other.

Starter code

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.