gpt4 book ai didi

python - Python Tornado 阻塞的困惑

转载 作者:行者123 更新时间:2023-11-28 22:40:57 25 4
gpt4 key购买 nike

所以我理解了 Tornado 本身是非阻塞事件循环 I/O 的基本思想,但是阻塞 IO 操作(如数据库访问)将导致 Tornado 在这些操作期间阻塞。

我不明白的是为什么 Tornado 在非阻塞操作期间似乎是阻塞的。

我在处理程序中有以下代码:

class MyHandler(BaseHandler):

def get(self):
x = 0
for i in xrange(0,500000000):
x = i

self.render("page_temp.html",
title="Page"
)

加载页面大约需要 20 秒。如果我打开另一个浏览器窗口并尝试加载任何其他页面,我会一直挂起,直到 20 秒页面加载完毕。会不会是因为两个请求都来自同一个用户?

最佳答案

您直接在您的处理程序中执行长时间的、受 CPU 限制的操作。 tornado 是单线程的,这意味着它无法在不阻塞所有其他请求的情况下在事件循环线程中执行 CPU 密集型工作。如果您需要执行 CPU 密集型工作,则必须在后台线程或进程中执行。

为了让这个方法并发处理请求,它需要看起来像这样:

from concurrent.futures import ThreadPoolExecutor
from tornado import gen
from tornado.web import RequestHandler

executor = ThreadPoolExecutor(8) # 8 Threads in the pool

class ThreadPoolHandler(RequestHandler):

def _do_loop(self):
x = 0
for i in xrange(0,500000000):
x = i

@gen.coroutine
def get(self):
yield executor.submit(self._do_loop) # Run through the loop without blocking tornado
self.render("page_temp.html",
title="Page"
)

通过使用 ThreadPoolExecutor 在后台线程中运行昂贵的 for 循环,tornado 可以在等待 CPU 工作完成的同时继续为其他请求提供服务。

关于python - Python Tornado 阻塞的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33156087/

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