Bounded Blocking Queue
medium · producer consumer
Implement BlockingQueue(capacity), where capacity >= 1. Simulate blocking deterministically; never start threads. put(worker, value) gives an integer directly to the oldest waiting consumer, else appends it if space exists, else queues this producer's pending write. It returns 'done' for immediate completion or 'blocked' for a pending write. take(worker) removes the oldest value, then admits the oldest pending producer if any; on an empty queue it queues a waiting consumer. take returns 'done' or 'blocked'. Every completed take appends [worker, value] to a delivery log. deliveries() returns the full log without clearing it; contents() returns the queued values in FIFO order. Workers have at most one pending operation. Pending operations complete automatically in FIFO order when another operation enables them. put/take are atomic; a blocked producer's value is not lost or duplicated.
Examples (JSON; null means Python None):
Input: {"capacity": 1, "operations": [["put", ["p", 1]], ["put", ["q", 2]], ["take", ["c"]], ["contents", []], ["take", ["d"]], ["deliveries", []]]}
Output: ["done", "blocked", "done", [2], "done", [["c", 1], ["d", 2]]]
Input: {"capacity": 2, "operations": [["take", ["a"]], ["take", ["b"]], ["put", ["p", 9]], ["put", ["q", 8]], ["deliveries", []], ["contents", []]]}
Output: ["blocked", "blocked", "done", "done", [["a", 9], ["b", 8]], []]
Starter code
class BlockingQueue:
def __init__(self, capacity: int):
"""Implement this operation according to the statement."""
pass
def put(self, worker: str, value: int) -> str:
"""Implement this operation according to the statement."""
pass
def take(self, worker: str) -> str:
"""Implement this operation according to the statement."""
pass
def deliveries(self) -> list[list]:
"""Implement this operation according to the statement."""
pass
def contents(self) -> list[int]:
"""Implement this operation according to the statement."""
pass
Loading editor…
Each test has a five-second execution limit. Your practice drafts and solved progress stay in this browser.
Return to the Python compiler