Feb-07-2022, 06:23 PM
I have the following code:
OK, this is the wanted result for me but i can't understand how asyncio does this. At which exact point of the code the while loop "breaks", or yields or whatever?
Maybe at "name = await q.get()" it sees that there is nothing else in the queue and yields (or returns) from the say_hello coroutine function?
import asyncio PARALLEL_DOWNLOADS = 4 names = ['Aris', 'Kostas', 'Nikos', 'Makis', 'Christos', 'Andreas', 'Vasilis', 'Thanasis', 'Petros', 'Pavlos'] async def say_hello(q): while True: name = await q.get() print('Hello {}'.format(name)) q.task_done() print('After task done') async def main(): q = asyncio.Queue() for name in names: q.put_nowait(name) workers = [] for _ in range(PARALLEL_DOWNLOADS): worker = asyncio.create_task(say_hello(q)) workers.append(worker) await q.join() for worker in workers: worker.cancel() await asyncio.gather(*workers, return_exceptions=True) asyncio.run(main())Here when all the queue data has been consumed the while loop in the say_hello function breaks at the end of the loop. And this without any break, continue or return statement! I would say "automagically".
OK, this is the wanted result for me but i can't understand how asyncio does this. At which exact point of the code the while loop "breaks", or yields or whatever?
Maybe at "name = await q.get()" it sees that there is nothing else in the queue and yields (or returns) from the say_hello coroutine function?