Concurrency · 9 / 15 Exercise Medium

Producer and consumer

Objective

The producer-consumer pattern connects two parts through a queue with limited capacity. Use queue.Queue(maxsize=...) from the queue module, the thread-safe queue of the standard library. Real threads cannot be created in the browser, so the program simulates the situation in a deterministic way.

Instructions

  • Read the queue capacity and an integer n of events. Each event is P x (produce x) or C (consume).
  • Producing uses put_nowait: if it fits show Produced: x; if the queue is full (queue.Full), show Queue full: x rejected.
  • Consuming uses get_nowait: show Consumed: x with the oldest element (FIFO); if it is empty (queue.Empty), show Queue empty.
  • At the end show Pending: k with qsize().
Input
2
7
P x
P y
P z
C
P w
C
C
Output
Produced: x
Produced: y
Queue full: z rejected
Consumed: x
Produced: w
Consumed: y
Consumed: w
Pending: 0

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise