为什么 asyncio.get_event_loop 方法会检查当前线程是否为主线程? [英] Why asyncio.get_event_loop method checks if the current thread is the main thread?

查看:90
本文介绍了为什么 asyncio.get_event_loop 方法会检查当前线程是否为主线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在 asyncio 中使用 get_event_loop 方法 (source) 正在检查当前线程是否是主线程(请参阅下面代码段中我的评论)?

Why get_event_loop method in asyncio (source) is checking if the current thread is the main thread (see my comment in the snippet below)?

def get_event_loop(self):
    """Get the event loop.

    This may be None or an instance of EventLoop.
    """
    if (self._local._loop is None and
        not self._local._set_called and
        isinstance(threading.current_thread(), threading._MainThread)):  # <- I mean this thing here
        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 支持自动创建事件循环,而无需通过调用 new_event_loop()set_event_loop().由于事件循环的创建成本适中,并且会消耗一些操作系统资源,因此它不会在导入时自动创建,而是按需创建,特别是在第一次调用 get_event_loop().(此功能大部分已被 asyncio.run 总是会创建一个新的事件循环,然后自动创建的循环会导致问题.)

For convenience, asyncio supports automatically creating an event loop without having to go through calls to new_event_loop() and set_event_loop(). As the event loop is moderately expensive to create, and consumes some OS resources, it's not created automatically on import, but on-demand, specifically on the first call to get_event_loop(). (This feature is mostly obsoleted by asyncio.run which always creates a new event loop, and then the auto-created one can cause problems.)

然而,这种便利是为主线程保留的——任何其他线程都必须显式设置事件循环.这有几个可能的原因:

This convenience, however, is reserved for the main thread - any other thread must set the event loop explicitly. There are several possible reasons for this:

  • 防止混淆 - 您不希望从任意线程意外调用 get_event_loop() 来为该线程分配主"(自动创建的)事件循环;
  • 某些 asyncio 功能在或要求事件循环在主线程中运行时效果最佳 - 例如,子进程信号处理.
  • preventing confusion - you don't want an accidental call to get_event_loop() from an arbitrary thread to appropriate the "main" (auto-created) event loop for that thread;
  • some asyncio features work best when or require that the event loop is run in the main thread - for example, subprocesses and signal handling.

这些问题也可以通过在每个线程中自动创建一个新的事件循环来避免,该循环调用get_event_loop(),但这会很容易意外创建多个事件其协程无法相互通信的循环,这将违背 asyncio 的设计.所以剩下的选择是让代码对主线程进行特殊处理,鼓励开发人员使用该线程来执行异步代码.

These problems could also be avoided by automatically creating a new event loop in each thread that invokes get_event_loop(), but that would make it easy to accidentally create multiple event loops whose coroutines would be unable to communicate with each other, which would go against the design of asyncio. So the remaining option is for the code to special-case the main thread, encouraging developers to use that thread for executing asyncio code.

这篇关于为什么 asyncio.get_event_loop 方法会检查当前线程是否为主线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆