【问题标题】:Python3 asyncio There is no current event loop in thread when spawn a new threadPython3 asyncio产生新线程时线程中没有当前事件循环
【发布时间】:2020-06-13 03:08:36
【问题描述】:
我可以通过这个例子轻松重现这个问题:
from threading import Thread
import asyncio
def func():
asyncio.get_event_loop()
Thread(target=func).start()
根据文档:
如果当前OS线程中没有设置当前事件循环,OS线程是main,并且还没有调用set_event_loop(),asyncio会创建一个新的事件循环,并将其设置为当前。
【问题讨论】:
标签:
python-3.x
python-asyncio
coroutine
【解决方案1】:
新事件循环的自动分配只发生在主线程上。来自events.py中的asyncio DefaultEventLoopPolicy 来源
def get_event_loop(self):
"""Get the event loop for the current context.
Returns an instance of EventLoop or raises an exception.
"""
if (self._local._loop is None and
not self._local._set_called and
isinstance(threading.current_thread(), threading._MainThread)):
self.set_event_loop(self.new_event_loop())
if self._local._loop is None:
raise RuntimeError('There is no current event loop in thread %r.'
% threading.current_thread().name)
return self._local._loop
所以对于非主线程,你必须手动设置事件循环asyncio.set_event_loop(asyncio.new_event_loop())