linux-sysprog · intermediate · ~15 min

Bounded buffer occupancy

Model a bounded producer/consumer queue.

Challenge

A bounded producer/consumer buffer blocks producers when full and consumers when empty. Replay an operation trace (blocking modelled as a no-op) and report the final item count.

Task

Implement int buffer_after(const char *ops, int cap) that replays ops on a buffer of capacity cap and returns how many items remain.

Input

  • ops: a string where 'p' = produce one item (ignored if the buffer is full) and 'c' = consume one (ignored if empty).
  • cap: the buffer capacity.

Output

The item count after replaying all ops (between 0 and cap).

Example

buffer_after("ppppp", 3)   ->   3   (fills, then produces are dropped)
buffer_after("ppcc", 5)    ->   0
buffer_after("pppc", 5)    ->   2

Edge cases

  • Produce when full: no-op.
  • Consume when empty: no-op.

Input format

ops: string of 'p' (produce) and 'c' (consume); cap: buffer capacity.

Output format

Item count after all ops (0..cap).

Constraints

Produce when full and consume when empty are no-ops.

Starter code

int buffer_after(const char *ops, int cap) {
    /* TODO */
    return 0;
}

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