A producer thread hands items to a consumer through a fixed-size circular buffer. When it's full the producer waits (back-pressure); when it's empty the consumer waits.
Implement RingBuffer(capacity):
- Keep items in
self.buf, a list of lengthcapacitymade once in__init__. Track the read position and item count yourself, wrapping with% capacity(nodeque,queue.Queue,pop(0)or growing the list). put(item): block while full, then add at the back.get(): block while empty, then remove and return the front item.__len__(): items stored.
Items come out in order; any value, including None, is an item.
rb = RingBuffer(2)
rb.put("a"); rb.put("b") # full: a third put() would block
rb.get() # "a", frees a slot
rb.put("c") # goes into slot 0 (wrap-around)
rb.get(), rb.get() # "b", "c"; now empty, so the next get() blocks
capacity >= 1; several producers and consumers may share it. Don't sleep or busy-wait.
Show hint
write to buf[(head + size) % capacity], read buf[head] and advance head; size tells full from empty. Guard it with one Condition, using wait_for and notify_all.