Skip to content Skip to sidebar Skip to footer

Why Asyncio.get_event_loop Method Checks If The Current Thread Is The Main Thread?

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 e

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

Post a Comment for "Why Asyncio.get_event_loop Method Checks If The Current Thread Is The Main Thread?"