Error happen python3.6 while using tornado in multi threading

谁说我不能喝 提交于 2021-02-04 19:21:30

问题


I just simply use the tornado application together with threading as the following code:

def MakeApp():
    return tornado.web.Application([(r"/websocket", EchoWebSocket), ])

def run_tornado_websocket():
    app = MakeApp()
    http_server = tornado.httpserver.HTTPServer(app, ssl_options={
        "certfile": os.path.join(os.path.abspath("."), "server.crt"),
        "keyfile": os.path.join(os.path.abspath("."), "server_no_passwd.key"),
        })

    http_server.listen(options.port)
    tornado.ioloop.IOLoop.current().start()

if __name__ == '__main__':
    threads = []
    t = threading.Thread(target=run_tornado_websocket, args=())
    threads.append(t)
    for t in threads:
        t.start()

It works fine on python3.5.But it fails on python3.6 and the lasted tornado.It gets the error:

Exception in thread Thread-1:
Traceback (most recent call last):
  File "D:\python3\lib\threading.py", line 916, in _bootstrap_inner
    self.run()
  File "D:\python3\lib\threading.py", line 864, in run
    self._target(*self._args, **self._kwargs)
  File "D:\ssl\ws_server.py", line 49, in run_tornado_websocket
    http_server.listen(options.port)
  File "D:\python3\lib\site-packages\tornado\tcpserver.py", line 145, in listen
    self.add_sockets(sockets)
  File "D:\python3\lib\site-packages\tornado\tcpserver.py", line 159, in add_sockets
    sock, self._handle_connection)
  File "D:\python3\lib\site-packages\tornado\netutil.py", line 219, in add_accept_handler
    io_loop = IOLoop.current()
  File "D:\python3\lib\site-packages\tornado\ioloop.py", line 282, in current
    loop = asyncio.get_event_loop()
  File "D:\python3\lib\asyncio\events.py", line 694, in get_event_loop
    return get_event_loop_policy().get_event_loop()
  File "D:\python3\lib\asyncio\events.py", line 602, in get_event_loop
% threading.current_thread().name)
RuntimeError: There is no current event loop in thread 'Thread-1'.

I think there are some changes in IOLOOP in python3.6.But I don't know how to fix this and really want to know the reason.


回答1:


Starting in Tornado 5.0, the asyncio event loop is used by default. asyncio has some extra restrictions because starting event loops on threads other than the main thread is an uncommon pattern and is often a mistake. You must tell asyncio that you want to use an event loop in your new thread with asyncio.set_event_loop(asyncio.new_event_loop()), or use asyncio.set_event_loop_policy(tornado.platform.asyncio.AnyThreadEventLoopPolicy()) to disable this restriction.



来源:https://stackoverflow.com/questions/51038793/error-happen-python3-6-while-using-tornado-in-multi-threading

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!