linux-sysprog · intermediate · ~15 min
Verify the global lock-ordering rule.
The standard way to prevent deadlock is a global lock-ordering rule: every thread acquires locks in the same order. Verify two threads obey it.
Implement int same_lock_order(const int *a, const int *b, int n) that returns 1 if the two n-length acquisition sequences are identical element by element, else 0.
a: thread A's lock-acquisition order (n lock ids).b: thread B's lock-acquisition order (n lock ids).n: sequence length.1 if a[i] == b[i] for all i, else 0.
same_lock_order([1,2,3], [1,2,3], 3) -> 1
same_lock_order([1,2,3], [3,2,1], 3) -> 0
n == 0: vacuously identical, return 1.a, b: two length-n lock-order arrays; n: their length.
1 if the orders match element-by-element, else 0.
Both arrays have the same length n.
int same_lock_order(const int *a, const int *b, int n) {
/* TODO */
return 0;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.