linux-sysprog · intermediate · ~15 min
Validate correct mutex usage.
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.
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.
ops: a string of 'l' and 'u' characters.1 if the trace is valid, else 0.
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)
ops: string of 'l' (lock) and 'u' (unlock) on one mutex.
1 if the trace is a valid lock/unlock sequence, else 0.
No double-lock, no unlock-while-free, must end unlocked.
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.