linux-sysprog · intermediate · ~15 min

Consistent lock order

Verify the global lock-ordering rule.

Challenge

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.

Task

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.

Input

  • a: thread A's lock-acquisition order (n lock ids).
  • b: thread B's lock-acquisition order (n lock ids).
  • n: sequence length.

Output

1 if a[i] == b[i] for all i, else 0.

Example

same_lock_order([1,2,3], [1,2,3], 3)   ->   1
same_lock_order([1,2,3], [3,2,1], 3)   ->   0

Edge cases

  • n == 0: vacuously identical, return 1.

Input format

a, b: two length-n lock-order arrays; n: their length.

Output format

1 if the orders match element-by-element, else 0.

Constraints

Both arrays have the same length n.

Starter code

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.