Skip to content
BytePatterns

Bounded Buffer Hand-Offs

HardConcurrency#bounded-queue#event-simulation#fifo-fairness~35m

Problem

Producers and consumers share a blocking queue that holds at most capacity items. You get the calls in the order they happened: ("put", producer, item) or ("take", consumer). A put on a full queue blocks its producer, and a take on an empty queue blocks its consumer. Blocked callers wake in the order they blocked: a take that frees a slot lets the oldest blocked producer add its item, and a put while consumers are blocked hands its item straight to the oldest of them. With capacity 0 the queue stores nothing, so every item must pass directly from a producer to a consumer. Return the deliveries as (consumer, item) pairs in order, and the producers still blocked at the end.

Examples

Input:  capacity = 1, calls = put P1 a, put P2 b, take C1, take C2, take C1, put P1 c
Output: ([('C1', 'a'), ('C2', 'b'), ('C1', 'c')], [])
Why:    P2 blocks until C1's take makes room; C1's second take blocks until c arrives
Input:  capacity = 2, calls = take C1, put P1 x, put P1 y, put P2 z, put P2 w
Output: ([('C1', 'x')], ['P2'])
Why:    x goes straight to the waiting C1, y and z fill the queue, and w has nowhere to go
Input:  capacity = 0, calls = put P1 q, take C1, take C2
Output: ([('C1', 'q')], [])
Why:    edge case, a zero-capacity queue is a rendezvous, so C2 is left waiting

Hints

0 / 3

Stuck on the idea rather than the code? Producer and Consumer covers it.