Skip to main content

python asyncio.create_task tasks exiting earlier than expected?

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?



source https://stackoverflow.com/questions/71541726/python-asyncio-create-task-tasks-exiting-earlier-than-expected

Comments