Ziq*_*Liu 6 coroutine python-3.x python-asyncio
我可以用这个例子轻松重现这个问题:
from threading import Thread
import asyncio
def func():
asyncio.get_event_loop()
Thread(target=func).start()
Run Code Online (Sandbox Code Playgroud)
根据文件:
如果当前 OS 线程中没有设置当前事件循环,OS 线程是主线程,并且尚未调用 set_event_loop(),asyncio 将创建一个新的事件循环并将其设置为当前事件循环。
syf*_*uqs 10
新事件循环的自动分配仅发生在主线程上。来自 asyncio DefaultEventLoopPolicy 中的源码events.py
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
Run Code Online (Sandbox Code Playgroud)
所以对于非主线程,你必须手动设置事件循环 asyncio.set_event_loop(asyncio.new_event_loop())