execute multiple functions concurrently using asyncio

PHOTO EMBED

Mon Apr 11 2022 08:37:29 GMT+0000 (Coordinated Universal Time)

Saved by @taha #python

import asyncio


async def say_hi():
    while True:
        print('hi')
        await asyncio.sleep(1)


async def say_hello():
    while True:
        print('Helloooooooooo')
        await asyncio.sleep(2)


async def main():
    task1 = loop.create_task(say_hi())
    task2 = loop.create_task(say_hello())
    await asyncio.wait([task1, task2])

    """This is also correct"""
    # await asyncio.gather(say_hi(), say_hello())


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

    try:
        loop.run_until_complete(main())
    finally:
        loop.close()
content_copyCOPY