A bounded blocking queue is the backbone of the producer–consumer pattern: producers hand off work, consumers pick it up, and the fixed capacity provides backpressure so fast producers cannot run away from slow consumers. The tricky part is that many threads touch it at once, so it must be correct under concurrency.
Implement BlockingQueue with a fixed capacity:
put(self, item) -> None — enqueue item. If the queue is full, block until space is available.get(self) — dequeue and return the oldest item. If the queue is empty, block until an item is available.size(self) -> int — return the current number of items.Requirements:
put waits when full, get waits when empty — no busy-waiting, no dropped or duplicated itemsputs (with a single consumer, items come out in the order they went in)Constraints:
capacity >= 1threading primitives (Condition, Lock, Semaphore) — a collections.deque is fine for the underlying buffer, but the synchronization is yoursget on an empty queue must block, not return a sentinelOfficial solution locked
Give the problem a real attempt before peeking — revealing it affects your credit for this problem for 4 hours.