I have a web app built on a Python 3.5+ async framework (apistar, sanic, etc). The app makes various IO calls - to a database, Redis, etc - which are also async.
Some docs recommend using an additional event loop:
import asyncio
import peewee
from peewee_async import Manager, PostgresqlDatabase
loop = asyncio.new_event_loop() # Note: custom loop!
database = PostgresqlDatabase('test')
objects = Manager(database, loop=loop)
It's my understanding that await
statements allow the event loop to context switch whenever it hits IO, so additional event loops seem completely unnecessary.
What is the benefit of using an additional event loop, and when should additional loops be used?
The Event Loop has one simple job — to monitor the Call Stack and the Callback Queue. If the Call Stack is empty, the Event Loop will take the first event from the queue and will push it to the Call Stack, which effectively runs it. Such an iteration is called a tick in the Event Loop.
MainAppLoop - This is the main loop of an application. Typically this is found at the bottom of the main. It's exit usually signals the desire for the application to close down. There can only be one of these per application. ThreadLoop - This is the loop commonly found at the bottom of a UI Thread's main procedure.
No. It is not "optimized polling." An event-loop uses interrupt-driven I/O instead of polling. While, Until, For, etc. loops are polling loops.
As always, calling a function creates a new stack frame for that function's use. The processing of functions continues until the stack is once again empty. Then, the event loop will process the next message in the queue (if there is one).
You should use multiple event loops one by one when you run your tests, so each test case is run against its own event loop.
You may have to use multiple loops simultaneously depending on requirements of underlying frameworks. In example pyzmq
and quamash
require their own event loop.
You may want to use multiple loops simultaneously if you need better control over task execution. In example when you want to explicitly group tasks and decide which group should be executed.
Keep in mind that current implementation allows to run only one loop per thread at a time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With