问题描述
我有一个线程调用 asyncio 循环,但这会导致上述异常:
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'.
这个问题:运行时错误:async + apscheduler 中的线程中没有当前事件循环 遇到了同样的问题,但是他们指的是我没有的调度程序.
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.
我的代码如下:
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()
推荐答案
新线程没有事件循环,所以你必须明确地传递和设置它:
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()
此外,p.join()
不会正确终止您的脚本,因为您永远不会停止服务器,因此您的循环将继续运行,大概会挂断线程.在加入线程之前,您应该像 loop.call_soon_threadsafe(ws.shutdown)
一样调用 smth,最好等待服务器正常关闭.
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.
这篇关于RuntimeError: 线程 'Thread-1' 中没有当前事件循环,多线程和异步错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!