Skip to content Skip to sidebar Skip to footer

Asyncio Doesn't Execute The Tasks Asynchronously

I'm playing around with asyncio module of Python and I don't know what's the problem with my simple code. It doesn't execute the tasks asynchronously. #!/usr/bin/env python3 i

Solution 1:

You are calling the functions sequentially, so the code also executes sequentially. Remember that await this means "do this and wait for it to return" (but in the meantime, if this chooses to suspend execution, other tasks which have already started elsewhere may run).

If you want to run the tasks asynchronously, you need to:

async def main():
    await msg('Hello World!')
    task1 = asyncio.ensure_future(print_alp())
    task2 = asyncio.ensure_future(print_num())
    await asyncio.gather(task1, task2)
    await msg('Hello Again!')

See also the documentation of the asyncio.gather function. Alternatively, you could also use asyncio.wait.

Solution 2:

You're encountering a common source of confusion with await statements, which is that they behave sequentially for 'child' coroutines but they behave asynchronously for 'neighbouring' coroutines.

For example:

import asyncio

asyncdefchild():
    i = 5while i > 0:
        print("Hi, I'm the child coroutine, la la la la la")
        await asyncio.sleep(1)
        i -= 1asyncdefparent():
    print("Hi, I'm the parent coroutine awaiting the child coroutine")
    await child() # this blocks inside the parent coroutine, but not the neighbourprint("Hi, I'm the parent, the child coroutine is now done and I can stop waiting")

asyncdefneighbour():
    i = 5while i > 0:
        await asyncio.sleep(1)
        print("Hi, I'm your neighbour!")
        i -= 1asyncdefmy_app():
    # start the neighbour and parent coroutines and let them coexist in Task wrappersawait asyncio.wait([neighbour(), parent()])

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(my_app())

Which will output:

Hi, I'm the parent coroutine awaiting the child coroutine
Hi, I'm the child coroutine, la la la la la
Hi, I'm the child coroutine, la la la la la
Hi, I'm your neighbour!
Hi, I'm the child coroutine, la la la la la
Hi, I'm your neighbour!
Hi, I'm the child coroutine, la la la la la
Hi, I'm your neighbour!
Hi, I'm the child coroutine, la la la la la
Hi, I'm your neighbour!
Hi, I'm the parent, the child coroutine is now done and I can stop waiting
Hi, I'm your neighbour!

Process finished withexit code 0

Post a Comment for "Asyncio Doesn't Execute The Tasks Asynchronously"