asyncio queues in Python
A producer and consumer sharing an async queue.
import asyncio
async def producer(queue):
for job in ["resize", "encode", "upload"]:
await queue.put(job)
await queue.put(None) # sentinel
async def worker(queue, done):
while (job := await queue.get()) is not None:
done.append(job)
async def main():
queue, done = asyncio.Queue(), []
await asyncio.gather(producer(queue), worker(queue, done))
return done
finished = asyncio.run(main())
How it works
- The producer
puts jobs, then aNonesentinel. - The worker loops with
:=until the sentinel. gatherruns both coroutines together.
Keywords and builtins used here
asyncawaitdefformainproducerreturnwhileworker
The run, in numbers
- Lines
- 20
- Characters to type
- 394
- Tokens
- 118
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 64 seconds.
Step 4 of 4 in Async, step 27 of 53 in Pythonic Python.