RuntimeError: There is no current event loop in thread 'Thread-1' , multithreading and asyncio error

New thread doesn't have an event loop so you have to pass and set it explicitly:

def worker(ws, loop):
    asyncio.set_event_loop(loop)
    loop.run_until_complete(ws.start())

if __name__ == '__main__':
    ws = Server()
    loop = asyncio.new_event_loop()
    p = threading.Thread(target=worker, args=(ws, loop,))
    p.start()

Also, p.join() won't terminate your script correctly as you never stop the server so your loop will continue running, presumably hanging up the thread. You should call smth like loop.call_soon_threadsafe(ws.shutdown) before joining the thread, ideally waiting for the server's graceful shutdown.


I had this issue for running a Bokeh Server in a thread. When I tried to create the server = Server({'/': app}, port=0), I would get this error. From the Tornado documentation I found the following...

Class tornado.platform.asyncio.AnyThreadEventLoopPolicy[source]

Event loop policy that allows loop creation on any thread. The default asyncio event loop policy only automatically creates event loops in the main threads. Other threads must create event loops explicitly or asyncio.get_event_loop (and therefore IOLoop.current) will fail. Installing this policy allows event loops to be created automatically on any thread, matching the behavior of Tornado versions prior to 5.0 (or 5.0 on Python 2).

Usage:

asyncio.set_event_loop_policy(AnyThreadEventLoopPolicy())

http://www.tornadoweb.org/en/stable/asyncio.html#tornado.platform.asyncio.AnyThreadEventLoopPolicy