![](/img/trans.png)
[英]In python's Tornado framework, instance variable and class variable confusion
[英]Confusion about Python Tornado's blocking
因此,我了解基本概念,即Tornado本身不會通過事件循環I / O進行阻塞,但是阻塞IO操作(如數據庫訪問)將導致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工作完成的同時繼續滿足其他請求。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.