Python3 asyncio生成新线程时线程中没有当前事件循环

问题描述 投票:0回答:1

我可以通过此示例轻松重现此问题:

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个回答
0
投票

新事件循环的自动分配仅在主线程上发生。来自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())手动设置事件循环>

© www.soinside.com 2019 - 2024. All rights reserved.