Sobes.tech
Junior — Middle

Which method in the AsyncIO library is used for concurrently launching multiple coroutines?

sobes.tech AI

Answer from AI

In the AsyncIO library, the function asyncio.gather() is used to run multiple coroutines concurrently. It takes several coroutines and runs them in parallel, returning the result after all have completed.

Example of usage:

import asyncio

async def task(name, delay):
    await asyncio.sleep(delay)
    return f'Task {name} done'

async def main():
    results = await asyncio.gather(
        task('A', 2),
        task('B', 1),
        task('C', 3)
    )
    print(results)

asyncio.run(main())

In this example, three tasks are started simultaneously, and asyncio.gather waits for their completion, collecting the results into a list.