I’m getting started with asyncio
and created this:
import asyncio
async def handle_data(q):
while (item := await q.get()) is not None:
print(f'Consuming {item}')
async def main():
q = asyncio.Queue()
consumer = asyncio.create_task(handle_data(q))
for k in range(10):
print(f'Producing {k}')
await q.put(k)
await q.put(None)
await consumer
asyncio.run(main())
The script outputs
Producing 0
Producing 1
Producing 2
Producing 3
Producing 4
Producing 5
Producing 6
Producing 7
Producing 8
Producing 9
Consuming 0
Consuming 1
Consuming 2
Consuming 3
Consuming 4
Consuming 5
Consuming 6
Consuming 7
Consuming 8
Consuming 9
Why is the code running synchronously?
You need to sign in to view this answers
Leave feedback about this