linux-sysprog · intermediate · ~15 min

Are lock/unlock balanced?

Validate correct mutex usage.

Challenge

A non-recursive mutex can't be re-locked by its holder and must be released before the program ends. Validate a usage trace against those rules.

Task

Implement int locks_balanced(const char *ops) that replays a trace of 'l' (lock) and 'u' (unlock) on one mutex and returns 1 only if the trace is valid: never unlocks a free mutex, never locks an already-held mutex, and ends with the mutex unlocked. Otherwise return 0.

Input

  • ops: a string of 'l' and 'u' characters.

Output

1 if the trace is valid, else 0.

Example

locks_balanced("lulu")   ->   1
locks_balanced("llu")    ->   0   (lock while already held)
locks_balanced("u")      ->   0   (unlock while free)
locks_balanced("lul")    ->   0   (ends still held)

Edge cases

  • Empty string: valid (return 1) — starts and ends unlocked.

Input format

ops: string of 'l' (lock) and 'u' (unlock) on one mutex.

Output format

1 if the trace is a valid lock/unlock sequence, else 0.

Constraints

No double-lock, no unlock-while-free, must end unlocked.

Starter code

int locks_balanced(const char *ops) {
    /* TODO */
    return 0;
}

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.