aiohttp线程慢 [英] aiohttp slowness with threading

查看:357
本文介绍了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线程慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆