linux-sysprog · beginner · ~15 min

Critical section nesting

Track lock state at a point in time.

Challenge

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.

Task

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.

Input

  • ops: a string of 'l' and 'u' characters.
  • k: number of operations to replay (0..length).

Output

1 if the mutex is held immediately after the first k ops, else 0.

Example

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)

Edge cases

  • k == 0: nothing replayed, mutex free, return 0.

Input format

ops: string of 'l'/'u'; k: number of ops to replay.

Output format

1 if the mutex is held after the first k ops, else 0.

Constraints

k ranges from 0 to the length of ops.

Starter code

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.