Understanding event loops

In computer science, an event is an action intercepted by the program that can be managed by the program itself. As an example, an event could be the virtual pressure of a key by the user during interaction with the graphical interface, the pressure of a key on the physical keyboard, an external interrupt signal, or, more abstractly, the reception of data through the network. But more generally, any other form of event that has happened that can be detected and managed in some way.

Within a system, the entity that can generate events is called an event source, while the entity that deals with handling an event that occurs are an event handler.

The event loop programming construct realizes the functionality of managing events within a program. More precisely, the event loop acts cyclically during the whole execution of the program, keeping track of events that have occurred within a data structure to queue and then process them one at a time by invoking the event handler if the main thread is free.

The pseudocode of the event loop manager is shown here:

while (1) {
events = getEvents()
for (e in events)
processEvent(e)
}

All the events that are fed into the while loop are caught and then processed by the event handler. The handler that processes an event is the only activity taking place in the system. When the handler has ended, control passes to the next event scheduled.

asyncio provides the following methods to manage an event loop:

  • loop = get_event_loop(): This gets the event loop for the current context.
  • loop.call_later(time_delay,callback,argument): This arranges for the callback to be called after the given time_delay, in seconds.
  • loop.call_soon(callback, argument): This arranges for a callback to be called as soon as possible. The callback is called after call_soon() (https://docs.python.org/3/library/asyncio-eventloop.html) returns when control returns to the event loop.
  • loop.time(): This returns the current time as a float value (https://docs.python.org/3/library/functions.html), according to the event loop's internal clock.
  • asyncio.set_event_loop(): This sets the event loop for the current context to loop.
  • asyncio.new_event_loop(): This creates and returns a new event loop object according to this policy's rules.
  • loop.run_forever(): This runs until stop() (https://docs.python.org/3/library/asyncio-eventloop.html) is called.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.111.92