Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error happen python3.6 while using tornado in multi threading

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.

like image 945
user9993202 Avatar asked Apr 12 '26 07:04

user9993202


1 Answers

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.

like image 182
Ben Darnell Avatar answered Apr 17 '26 13:04

Ben Darnell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!