Interview Prep/Python for DevOps/Concurrency: threads, processes & asyncio

How does a producer/consumer pattern with `queue.Queue` work?

AdvancedConceptConcurrency: threads, processes & asyncio
Answer
import queue, threading
q: queue.Queue[str | None] = queue.Queue(maxsize=100)

def worker():
    while (item := q.get()) is not None:
        try:
            process(item)
        finally:
            q.task_done()
    q.task_done()

threads = [threading.Thread(target=worker, daemon=True) for _ in range(8)]
for t in threads: t.start()
for key in s3_keys(): q.put(key)        # blocks when full: back-pressure
for _ in threads: q.put(None)           # one sentinel per worker
q.join()

maxsize gives back-pressure so a fast producer does not fill memory.

All Python for DevOps questions Roadmap: Python for automation

More on Concurrency: threads, processes & asyncio