Sobes.tech
Junior — Middle

How can you perform the simultaneous execution of two tasks in asynchronous programming?

sobes.tech AI

Answer from AI

In Python, to run two asynchronous tasks concurrently, you can use the asyncio.gather() function. It allows you to start multiple coroutines in parallel and wait for their completion.

Example:

import asyncio

async def task1():
    await asyncio.sleep(1)
    return 'Task 1 completed'

async def task2():
    await asyncio.sleep(2)
    return 'Task 2 completed'

async def main():
    results = await asyncio.gather(task1(), task2())
    print(results)

asyncio.run(main())

In this example, task1 and task2 run simultaneously, and asyncio.gather collects their results after both have finished.