Why asyncio.get_event_loop method checks if the current thread is the main thread?

╄→гoц情女王★ 提交于 2020-01-16 05:09:23

问题


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 

回答1:


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:

  • 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.

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.



来源:https://stackoverflow.com/questions/55656726/why-asyncio-get-event-loop-method-checks-if-the-current-thread-is-the-main-threa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!