linux-sysprog · intermediate · ~15 min
Model a bounded producer/consumer queue.
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.
Implement int buffer_after(const char *ops, int cap) that replays ops on a buffer of capacity cap and returns how many items remain.
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.The item count after replaying all ops (between 0 and cap).
buffer_after("ppppp", 3) -> 3 (fills, then produces are dropped)
buffer_after("ppcc", 5) -> 0
buffer_after("pppc", 5) -> 2
ops: string of 'p' (produce) and 'c' (consume); cap: buffer capacity.
Item count after all ops (0..cap).
Produce when full and consume when empty are no-ops.
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.