Python asyncio 是否使用线程池?

Does Python asyncio use a thread pool?

我写了这段代码:

import asyncio
import threading
from aiohttp import ClientSession

async def fetch(url):
    async with ClientSession() as session:
        async with session.get(url) as response:
            response = await response.read()
            print(threading.current_thread().name)


loop = asyncio.get_event_loop()

tasks = [asyncio.ensure_future(fetch("http://example.com")) for i in range(5)]

loop.run_until_complete(asyncio.wait(tasks))

每次都打印"MainThread"。这是否意味着所有请求都使用同一个主线程并发执行,而不是使用线程池中的线程来执行每个请求,或者线程是否被抽象化?

这 post 似乎表明实际上 Python 有一个线程池用于这些异步任务: http://skipperkongen.dk/2016/09/09/easy-parallel-http-requests-with-python-and-asyncio/

It prints out "MainThread" every time. Does this mean that all of the requests are being executed concurrently using the same main thread and it's not using threads from a thread pool to execute each request or are the threads being abstracted?

它不使用工作线程,asyncio只会使用主线程。并发是通过使用 Python 生成器(阅读 coroutines)的协作式多任务处理实现的。

This post seems to show that in fact there is a thread pool ...

asyncio 模块一样,您链接的博客 post 明确使用了 concurrent.futures 模块。该代码中的 ThreadPoolExecutor class 将产生工作线程。但是您问题中的示例代码不会。