aiohttp线程慢

编程入门 行业动态 更新时间:2024-10-26 19:40:59
本文介绍了aiohttp线程慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我从>如何运行aiohttp服务器复制了代码在一个线程中?。运行正常。所以我要增加一秒钟的睡眠时间。当我同时启动10个请求时。平均响应时间为9秒。这是为什么?并非所有请求都会在1秒后回来吗?

I copied the code from How to run an aiohttp server in a thread?. It runs fine. So I am adding one second sleep. When I launch 10 requests at the same time. The average response time is 9 seconds. Why is that? Wouldn't all requests coming back in a little bit over 1 second?

import asyncio import threading from aiohttp import web import time loop = asyncio.get_event_loop() def say_hello(request): time.sleep(1) return web.Response(text='Hello, world') app = web.Application(debug=True) app.add_routes([web.get('/', say_hello)]) handler = app.make_handler() server = loop.create_server(handler, host='127.0.0.1', port=8080) def aiohttp_server(): loop.run_until_complete(server) loop.run_forever() t = threading.Thread(target=aiohttp_server) t.start()

推荐答案

您要在第二个线程中启动服务器,但是所有请求都来自同一线程。对 time.sleep 的调用将阻止该线程,并且不会屈服于事件循环,因此将有效地串行处理请求。

You are starting the server in a second thread, but all of the requests are served from the same thread. The call to time.sleep blocks this thread and does not yield to the event loop so that the requests are effectively processed serially.

如果您确实希望使用睡眠来延迟响应,则可以使用 asyncio.sleep 代替,这会导致事件循环。

If you genuinely want to use sleep for a delay in the response you could use asyncio.sleep instead, which yields to the event loop.

但是我希望您将其用作另一个阻止功能的占位符。在这种情况下,您需要在主服务器的另一个线程中运行它。以下示例显示了如何使用 run_in_executor 和 asyncio.wait 来执行此操作。

However I expect you are using it as a placeholder for another blocking function. In this case you need to run this in another thread to the main server. The example below shows how to do this using run_in_executor and asyncio.wait.

import asyncio from aiohttp import web from concurrent.futures import ThreadPoolExecutor import time def blocking_func(seconds: int) -> int: time.sleep(seconds) return seconds async def view_page(request: web.Request): seconds = int(request.query.get("seconds", 5)) executor = request.app["executor"] loop = asyncio.get_event_loop() task = loop.run_in_executor(executor, blocking_func, seconds) completed, pending = await asyncio.wait([task]) result = task.result() return web.Response(text=f"Waited {result} second(s).") def create_app(): app = web.Application() app.add_routes([web.get("/", view_page)]) executor = ThreadPoolExecutor(max_workers=3) app["executor"] = executor return app if __name__ == "__main__": app = create_app() web.run_app(app)

更多推荐

aiohttp线程慢

本文发布于:2023-11-23 10:19:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1621091.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:线程   aiohttp

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!