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.
More on Concurrency: threads, processes & asyncio
What is the GIL, and what does it mean for DevOps scripts?IntermediateHow do you use `ThreadPoolExecutor` for parallel API calls?BeginnerThreads vs processes vs asyncio: how do you choose?IntermediateWhat is a race condition, and how do you prevent one in threaded code?IntermediateWhat are coroutines, `async def` and `await`?IntermediateHow do you run many async tasks concurrently with a limit?Intermediate