gpt4 book ai didi

python - Python asyncio 是否使用线程池?

转载 作者:太空狗 更新时间:2023-10-29 20:53:14 25 4
gpt4 key购买 nike

我写了这段代码:

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”。这是否意味着所有请求都使用同一个主线程并发执行,而不是使用线程池中的线程来执行每个请求,或者线程是否被抽象化?

这篇文章似乎表明实际上有一个 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 模块,您链接的博文还明确使用了 concurrent.futures 模块。该代码中的 ThreadPoolExecutor 类将产生工作线程。但是您问题中的示例代码不会。

关于python - Python asyncio 是否使用线程池?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45427784/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com