我正在尝试在多个线程中运行多个 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?
另外,我发现删除最后 3 行并替换为tornado.ioloop.IOLoop.instance().start
非常适合单线程。但是单例和自创建的IOLoop有什么区别呢?
我是龙卷风的新手,欢迎任何答案。
一般来说,在构造异步对象时,您应该使用 IOLoop.current 作为默认值,而当您打算从另一个线程与主线程通信时,则应使用 IOLoop.instance。
IOLoop.current http://www.tornadoweb.org/en/stable/ioloop.html#tornado.ioloop.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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)