Interview challenge · medium · concurrency, threads, bounded-buffer
Producer-Consumer Problem
El reto
El enunciado va en inglés, igual que en el vídeo.
Two threads share a bounded buffer. The producer adds items and must wait while the buffer is full; the consumer removes them and must wait while it is empty. Every item has to arrive exactly once and in order.
Example
buffer capacity 2, the producer makes 1..6
consumer: got 1, got 2, got 3, got 4, got 5, got 6Idea: protect the buffer with a lock, and let each thread sleep on a condition variable until it can go on: the producer while the buffer is full, the consumer while it is empty. After each change the thread wakes the other one. The waits are while loops, not if, because a thread must check the buffer again after it wakes up. The C version keeps the items in a ring buffer (head and count); Python uses a deque. Only the consumer prints, so the output is always the same. In real code, Python's queue.Queue and Java's BlockingQueue already do all of this.
La solución
# Producer-Consumer Problem - ayotl.dev
from collections import deque
from threading import Condition, Thread
CAP, N = 2, 6 # buffer size, items
buf = deque()
cv = Condition()
def produce():
for item in range(1, N + 1):
with cv:
while len(buf) == CAP:
cv.wait() # full
buf.append(item)
cv.notify()
def consume():
for _ in range(N):
with cv:
while not buf:
cv.wait() # empty
item = buf.popleft()
cv.notify()
print("got", item)
ts = [Thread(target=produce),
Thread(target=consume)]
for t in ts:
t.start()
for t in ts:
t.join()
print("done")
$ python3 producer_consumer.py
got 1
got 2
got 3
got 4
got 5
got 6
done