首页 > 解决方案 > Python3 asyncio产生新线程时线程中没有当前事件循环

问题描述

我可以用这个例子很容易地重现这个问题:

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.xpython-asynciocoroutine

解决方案


新事件循环的自动分配只发生在主线程上。来自 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

所以对于非主线程,你必须手动设置事件循环asyncio.set_event_loop(asyncio.new_event_loop())


推荐阅读