Skip to content
BytePatterns

Producer and Consumer

Concurrency: lesson 6 of 10

A bounded belt between the two sides.

Lesson 6 of 10 · 5 min

Producer and Consumer

Step 1 of 11

A queue of size 2 sits between the two sides. Neither knows the other exists.

The Idea

Producers put work in a queue, consumers take it out, and neither knows the other exists. The queue is bounded on purpose: a full queue blocks the producer, an empty one blocks the consumer, and both sides scale independently.

Real-World Example

A conveyor-belt sushi bar. The chef plates onto the belt without knowing who eats what; when the belt is full he stops plating and starts prepping. When it runs empty the diners simply wait, and nobody shouts an order across the room.

The Code

import queue, threading

belt = queue.Queue(maxsize=2)         # bounded: the chef waits when it is full

def diner():
    while True:
        plate = belt.get()
        if plate is None: break       # sentinel: the belt is closing
        print("served", plate)

t = threading.Thread(target=diner); t.start()
for plate in ["tuna", "egg", "eel"]:
    belt.put(plate)
belt.put(None)
t.join()

Your turn

Fill in the blank.

import queue

q = queue.Queue(maxsize=2)
q.put("a")
q.put("b")
print(q.full())      # True — a producer would block right here
q.get()
print(___)           # want 1

Mini quiz

1 / 3

A bounded queue gives you: