I have the following code:
import asyncio async def myfunc(i): print("hello", i) await asyncio.sleep(i) print("world", i) async def main(): asyncio.create_task(myfunc(2)) asyncio.create_task(myfunc(1)) asyncio.run(main())
It outputs:
hello 2 hello 1
Notice that world
isn’t printed anywhere. Why is the output we see being produced? I was expecting:
hello 2 hello 1 world 1 world 2
Because I thought that the asyncio.sleep(i)
calls would yield execution to the event loop, at which point the event loop would reschedule them after their respective wait times. Clearly I am misunderstanding. Can someone explain?
Advertisement
Answer
Found a much simpler solution than the one provided by @eyllanesc here. Turns out there is a function that implements it