![](/img/trans.png)
[英]How to use multiple ioloop in tornado and share data between the ioloop(s)?
[英]Tornado multiple IOLoop in multithreads
我試圖在多個線程中運行多個IOLoop,但我想知道IOLoop實際如何工作。
class WebThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self, name='WebThread')
def run(self):
curdir = os.path.dirname(os.path.realpath(__file__))
application = Application() #Very simple tornado.web.Application
http_server_api = tornado.httpserver.HTTPServer(application)
http_server_api.listen(8888)
logging.info('Starting application')
#tornado.ioloop.IOLoop.instance() is singleton, not for thread, right?
ioloop = tornado.ioloop.IOLoop()
ioloop.make_current()
ioloop.start()
根據文檔,我不能使用IOLoop.instance(),因為它是單例並且我正在線程中工作。 因此,我創建了自己的IOLoop。 但是這段代碼在端口8888上偵聽,但無法呈現任何網頁。 我想知道是否有任何遺漏,還是需要以某種方式將http_server綁定到IOLoop?
另外,我發現刪除最后三行並用tornado.ioloop.IOLoop.instance().start
替代對tornado.ioloop.IOLoop.instance().start
非常適用。 但是單例和自行創建的IOLoop有什么區別?
我是龍卷風的新手,歡迎回答。
通常,在構造異步對象時,應將IOLoop.current用作默認值,而在要從其他線程與主線程進行通信時,則應使用IOLoop.instance。
沒有參數的IOLoop.current
返回已創建的線程ioloop或調用IOLoop.instance()
。 並且HTTPServer(實際上在TCPServer中)使用IOLoop.current與ioloop進行交互,因此您唯一需要更改的是在HTTPServer之前創建ioloop,例如
class WebThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self, name='WebThread')
def run(self):
curdir = os.path.dirname(os.path.realpath(__file__))
ioloop = tornado.ioloop.IOLoop()
application = Application() #Very simple tornado.web.Application
http_server_api = tornado.httpserver.HTTPServer(application)
http_server_api.listen(8888)
logging.info('Starting application')
ioloop.start()
我也刪除了IOLoop.make_current
,因為它是多余的IOLoop()
將self設置為當前值。
上面的代碼將起作用,但僅在一個線程中起作用,因為默認情況下未啟用reuse_port。 您最終將得到:
OSError: [Errno 98] Address already in use
您可以啟用
http_server_api.bind(port=8888, reuse_port=True)
http_server_api.start()
而不是http_server_api.listen(8888)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.