Issue
I am having a thread which calls asyncio loops, however this causes the mentioned exception:
RuntimeError: There is no current event loop in thread 'Thread-1'.
This question: RuntimeError: There is no current event loop in thread in async + apscheduler came across the same problem, however they refered to a scheduler which I do not have.
My code is the following:
def worker(ws):
l1 = asyncio.get_event_loop()
l1.run_until_complete(ws.start())
l2 = asyncio.get_event_loop()
l2.run_forever()
if __name__ == '__main__':
ws = Server()
p = threading.Thread(target=worker,args=(ws,))
p.start()
while True:
try:
#...do sth
except KeyboardInterrupt:
p.join()
exit()
Solution
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.
Answered By - hoefling
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.