Python 为什么异步IO使用aiohttp发出请求仍然使用线程

Python 为什么异步IO使用aiohttp发出请求仍然使用线程,python,python-asyncio,aiohttp,Python,Python Asyncio,Aiohttp,我认为ayncio和coroutine的使用与线程无关,因为coroutine是在程序调度程序下运行的一种“线程”,所以每个进程应该只有一个线程运行。但当我在中运行示例时,代码如下所示: # modified fetch function with semaphore import random import asyncio from aiohttp import ClientSession async def fetch(url, session): async with sessi

我认为
ayncio
coroutine
的使用与线程无关,因为
coroutine
是在程序调度程序下运行的一种“线程”,所以每个进程应该只有一个线程运行。但当我在中运行示例时,代码如下所示:

# modified fetch function with semaphore
import random
import asyncio
from aiohttp import ClientSession

async def fetch(url, session):
    async with session.get(url) as response:
        delay = response.headers.get("DELAY")
        date = response.headers.get("DATE")
        print("{}:{} with delay {}".format(date, response.url, delay))
        return await response.read()


async def bound_fetch(sem, url, session):
    # Getter function with semaphore.
    async with sem:
        await fetch(url, session)


async def run(r):
    url = "http://localhost:8080/{}"
    tasks = []
    # create instance of Semaphore
    sem = asyncio.Semaphore(1000)

    # Create client session that will ensure we dont open new connection
    # per each request.
    async with ClientSession() as session:
        for i in range(r):
            # pass Semaphore and session to every GET request
            task = asyncio.ensure_future(bound_fetch(sem, url.format(i), session))
            tasks.append(task)

        responses = asyncio.gather(*tasks)
        await responses

number = 10000
loop = asyncio.get_event_loop()

future = asyncio.ensure_future(run(number))
loop.run_until_complete(future)

使用Windows的资源监视器,我发现代码在一个进程中创建了25个线程。

Python的标准库包含一个名为的模块,该模块允许使用
线程
实例并发运行Python代码
asyncio
aiohttp
不使用
threading
模块进行操作

Python本身可能使用OS(低级)线程作为实现细节——但这可能会在不同的平台和版本之间发生变化。例如,简单的
打印('hello world')的操作系统线程数;Windows 10中python 3.6.0的s=input()
为3


查看以查找windows中可能启动操作系统线程的线索。

默认情况下,aiohttp库使用线程进行并发DNS解析,以避免阻止IO循环,请参阅。如果需要异步DNS查找,则需要安装python包
aiodns
,该包反过来使用
pycares

然后,您可以执行以下操作:

async def fetch(url):
    resolver = aiohttp.AsyncResolver()
    connector = aiohttp.TCPConnector(resolver=resolver, family=socket.AF_INET)
    async with aiohttp.ClientSession(connector=connector) as session:
        async with session.get(url) as resp:
            if resp.status == 200:
                print("success!")
如果您想将
AsyncResolver
设置为全局默认值,这对我使用aiohttp 2.2.3是有效的:

import aiohttp.resolver
aiohttp.resolver.DefaultResolver = aiohttp.resolver.AsyncResolver