queue.Queue Decouples Producers And Consumers

A bounded queue.Queue plus a None sentinel lets producer and consumer threads hand work across safely, with blocking puts acting as built-in backpressure.

PythonResilience

Code

pythonsnippet
31 lines
import queue
import threading

jobs: queue.Queue = queue.Queue(maxsize=3)  # 有界队列:满了 put 会阻塞
results: list[str] = []


def producer() -> None:
    for n in range(5):
        jobs.put(f"job-{n}")  # 队列满时阻塞,天然限流
    jobs.put(None)  # None 作为关闭信号


def consumer() -> None:
    while True:
        job = jobs.get()
        if job is None:
            jobs.task_done()  # 哨兵也要配平计数
            break
        results.append(job.upper())
        jobs.task_done()


workers = [threading.Thread(target=producer), threading.Thread(target=consumer)]
for t in workers:
    t.start()
for t in workers:
    t.join()

print("processed:", results)
print("remaining:", jobs.qsize(), "unfinished:", jobs.unfinished_tasks)

How the snippet works

The working surface is the functions producer and consumer — everything else is wiring.

Repetition is confined to for n in range(5) — the rest of the file is straight-line.

Applying it

The primary signature is def producer() -> None

Output lines are prefixed (processed:, remaining:), making each step’s effect easy to spot.

Callers only need producer — everything else stays internal.

Statements that matter

def producer() -> None:
    for n in range(5):
        jobs.put(f"job-{n}")  # 队列满时阻塞,天然限流
    jobs.put(None)  # None 作为关闭信号
def consumer() -> None:
    while True:
        job = jobs.get()
        if job is None:
            jobs.task_done()  # 哨兵也要配平计数
            break
        results.append(job.upper())
        jobs.task_done()

Interactive Tools for This Topic

FAQ

Is anything beyond the standard library required?
Nothing beyond the standard library — the snippet is dependency-free. The file defines `producer`, `consumer` at load time.