Home > Blockchain >  asyncio - Code is executing synchronously
asyncio - Code is executing synchronously

Time:10-23

I'm a python beginner and taking from https://www.youtube.com/watch?v=iG6fr81xHKA&t=269s about the power of asyncio, I tried to use this example shown and repurpose it to execute 10 times. Here's a code snippet

def main(x):
    print("Hello")
    time.sleep(3)
    print("World!")

And so I tried to do it in a asyncio fashion however it doesn't execute asynchronously. Here's so far what I've tried. What am I doing wrong?

import time
import asyncio


async def main(x):
    print(f"Starting Task {x}")
    await asyncio.sleep(3)
    print(f"Finished Task {x}")


async def async_io():
    for i in range(10):
        await main(i)

if __name__ == "__main__":
    start_time = time.perf_counter()
    asyncio.run(async_io())
    print(f"Took {time.perf_counter() - start_time} secs")

I've also tried to use queue_task in asyncio.

CodePudding user response:

Using await, by definition, waits for the task main to finish. So your code as-is is no different from the synchronous code you posted above. If you want to run them at the same time (asynchronously), while waiting for the results, you should use asyncio.gather or asyncio.wait instead.

async def async_io():
    tasks = []
    for i in range(10):
        tasks  = [main(i)]
    await asyncio.gather(*tasks)

If you don't care to wait for all of the main() calls to finish, you can also just use asyncio.create_task(main(i)), which creates a Task object and schedule its execution in the background. In this case, def async_io() doesn't need to be async anymore.

  • Related