I have the following code:
JavaScript
x
13
13
1
import asyncio
2
3
async def myfunc(i):
4
print("hello", i)
5
await asyncio.sleep(i)
6
print("world", i)
7
8
async def main():
9
asyncio.create_task(myfunc(2))
10
asyncio.create_task(myfunc(1))
11
12
asyncio.run(main())
13
It outputs:
JavaScript
1
3
1
hello 2
2
hello 1
3
Notice that world
isn’t printed anywhere. Why is the output we see being produced? I was expecting:
JavaScript
1
5
1
hello 2
2
hello 1
3
world 1
4
world 2
5
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