linux-sysprog · intermediate · ~15 min

Are lock/unlock balanced?

Validate correct mutex usage.

Challenge

A trace uses 'l' (lock) and 'u' (unlock) on one non-recursive mutex. Implement int locks_balanced(const char *ops) returning 1 only if it never unlocks an unlocked mutex, never locks an already-held one, and ends 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.