Sobes.tech
Junior — Middle

How many threads are used when executing different coroutines in the asyncio library?

sobes.tech AI

Answer from AI

In Python's asyncio library, coroutines are executed within a single thread, meaning by default only one thread is used.

Asynchronous execution is achieved through an event loop, which switches between coroutines without blocking the thread. This allows efficient handling of input/output operations.

If multiple threads are needed, this is explicitly done using the concurrent.futures.ThreadPoolExecutor or ProcessPoolExecutor modules, but asyncio coroutines themselves do not create additional threads.

Example of running coroutines in a single thread:

import asyncio

async def task(name):
    print(f"Task {name} started")
    await asyncio.sleep(1)
    print(f"Task {name} completed")

async def main():
    await asyncio.gather(task('A'), task('B'))

asyncio.run(main())

In this example, both tasks run asynchronously within the same thread.