I'm trying to understand python asyncio lib, but it's a pain and each time I think i know how the code will behave, something suprises me.
I have the following code:
async def a():
while True:
task = asyncio.current_task() # asyncio.Task.current_task()
print(task.name)
await asyncio.sleep(0.5)
async def main():
tasks = []
for i in range(10):
c = a()
task = asyncio.create_task(c)
task.name = "task nr {}".format(i)
tasks.append(task)
for task in tasks:
await task
asyncio.run(main())
Would result with the following output as suspected:
task nr 0
task nr 1
task nr 2
task nr 3
task nr 4
task nr 5
task nr 6
task nr 7
task nr 8
task nr 9
and so on. On the other hand I have a code
async def a():
while True:
task = asyncio.current_task() # asyncio.Task.current_task()
print(task.name)
await asyncio.sleep(0.5)
async def main():
for i in range(10):
c = a()
task = asyncio.create_task(c)
task.name = "task nr {}".format(i)
await task
asyncio.run(main())
This time it outputs just "task nr 0".
In the first one creates 10 tasks and then starst all of them. The second one merges those two loops - why it affects behaviour of the program?