This is a followup question to /a/62529343/3358488
There, as well in other places, asyncio.create_task(c)
is described as “immediately” running the coroutine c
, when compared to simply calling the coroutine, which is then only executed when it is await
ed.
It makes sense if you interpret “immediately” as “without having to await
it”, but in fact a created task is not executed until we run some await
(possibly for other coroutines) (in the original question, slow_coro
started being executed only when we await fast_coro
).
However, if we do not run any await
at all, the tasks are still executed (only one step, not to completion) at the end of the program:
import asyncio
async def counter_loop(x, n):
for i in range(1, n + 1):
print(f"Counter {x}: {i}")
await asyncio.sleep(0.5)
return f"Finished {x} in {n}"
async def main():
slow_task = asyncio.create_task(counter_loop("Slow", 4))
fast_coro = asyncio.create_task(counter_loop("Fast", 2))
print("Created tasks")
for _ in range(1000):
pass
print("main ended")
asyncio.run(main())
print("program ended")
the output is
Created tasks
main ended
Counter Slow: 1
Counter Fast: 1
program ended
I am curious: why are the two created tasks executed at all if there was no await
being run anywhere?