Event loop

from Wikipedia, the free encyclopedia

An event loop ( English loop event , message dispatcher , message loop or message pump ) is in the computer science a program construct to events or messages waiting and within a program distributed. Event sources are queried and the function responsible for the event or message is called.

This loop often represents the central control flow and is therefore also referred to as the main loop or main event loop.

Examples

Many modern programs have a main loop. In contrast to before, the loop is interrupted by preemptive multitasking and only continued again when there is actually something to process. This is more efficient than actively waiting in cooperative multitasking .

Main loop of a program with cooperative multitasking

 function main
     initialize()
     while program_running
         message := get_next_message()
         if message = no_message then
             yield()
         else if message = quit then
             return
         end if
         process_message(message)
     repeat
 end function

In this example, returns get_next_messageimmediately no_messageif there are no new messages waiting. The function yield()voluntarily (cooperatively) returns the rest of the allocated processor time, so that the system can do something other than request new messages.

Main loop of an application with preemptive multitasking

 function main
     initialize()
     while program_running
         message := get_next_message()
         if message = quit then
             return
         end if
         process_message(message)
     repeat
 end function

In this example blocks get_next_message(without the function knowing anything about it) until a new message arrives. This means that no time is wasted querying non-existent messages.