progress

~/problems / Pools & pipelines / Ring buffers and producer/consumer pipelines

Blocking ring buffer

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy basics ~10 min

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 length capacity made once in __init__. Track the read position and item count yourself, wrapping with % capacity (no deque, 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.

Topic: Ring buffers and producer/consumer pipelines. Fixed-size circular buffers, head/tail indexes, back-pressure.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc