linux-sysprog · beginner · ~15 min
Track lock state at a point in time.
Code that runs between a lock and its unlock is inside the critical section, where shared state is safe to touch. Determine whether a given point in a trace is inside one.
Implement int in_critical_section(const char *ops, int k) that replays the first k operations of ops ('l'=lock, 'u'=unlock) and returns 1 if the mutex is held at that point, else 0.
ops: a string of 'l' and 'u' characters.k: number of operations to replay (0..length).1 if the mutex is held immediately after the first k ops, else 0.
in_critical_section("lu", 1) -> 1 (after 'l': held)
in_critical_section("lu", 2) -> 0 (after 'lu': free)
in_critical_section("lu", 0) -> 0 (nothing replayed)
k == 0: nothing replayed, mutex free, return 0.ops: string of 'l'/'u'; k: number of ops to replay.
1 if the mutex is held after the first k ops, else 0.
k ranges from 0 to the length of ops.
int in_critical_section(const char *ops, int k) {
/* TODO */
return 0;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.