Exercise: Producer/Consumer
This exercise puts the producer/consumer lesson into code.
Scenario
Model the core producer/consumer rendezvous as a single-threaded, deterministic simulation. The buffer holds at most three items in FIFO order. Rather than blocking a thread, it reports the boundary conditions — a full buffer rejects new items, and an empty buffer reports that there is nothing to consume.
Commands
| Command | Behavior | Output |
|---|---|---|
["produce", item] | Attempt to add item to the back of the buffer | "produced <item> (<newSize>/3)", or "full: <item> rejected" if the buffer already holds three items |
["consume"] | Remove the front item from the buffer | "consumed <item> (<newSize>/3)", or "empty" if the buffer holds nothing |
["size"] | Report the current number of items | "Size: <n>" |
A rejected produce leaves the buffer unchanged. A failed consume leaves the buffer unchanged.
Example
Input
7 produce apple produce banana produce cherry produce grape consume size consume
Output
produced apple (1/3) produced banana (2/3) produced cherry (3/3) full: grape rejected consumed apple (2/3) Size: 2 consumed banana (1/3)
Explanation
The first three produces fill the buffer to capacity, with sizes going from 1/3 to 3/3. The fourth produce of `grape` finds the buffer full and is rejected, leaving the buffer unchanged. The first consume removes `apple` from the front (FIFO order) and the buffer drops to 2/3. `size` reports 2. The next consume removes `banana`, leaving 1/3.
Your task
Implement the skeleton in the editor below so the commands produce the output described above.