HOME

TheInfoList



OR:

In
computer science Computer science is the study of computation, automation, and information. Computer science spans theoretical disciplines (such as algorithms, theory of computation, information theory, and automation) to Applied science, practical discipli ...
, the event loop is a programming construct or design pattern that waits for and dispatches events or messages in a
program Program, programme, programmer, or programming may refer to: Business and management * Program management, the process of managing several related projects * Time management * Program, a part of planning Arts and entertainment Audio * Programm ...
. The event loop works by making a request to some internal or external "event provider" (that generally blocks the request until an event has arrived), then calls the relevant event handler ("dispatches the event"). The event loop is also sometimes referred to as the message dispatcher, message loop, message pump, or run loop. The event-loop may be used in conjunction with a reactor, if the event provider follows the file interface, which can be selected or 'polled' (the Unix system call, not actual polling). The event loop almost always operates asynchronously with the message originator. When the event loop forms the central
control flow In computer science, control flow (or flow of control) is the order in which individual statements, instructions or function calls of an imperative program are executed or evaluated. The emphasis on explicit control flow distinguishes an '' ...
construct of a program, as it often does, it may be termed the main loop or main event loop. This title is appropriate, because such an event loop is at the highest level of control within the program.


Message passing

Message pumps are said to 'pump' messages from the program's message queue (assigned and usually owned by the underlying operating system) into the program for processing. In the strictest sense, an event loop is one of the methods for implementing
inter-process communication In computer science, inter-process communication or interprocess communication (IPC) refers specifically to the mechanisms an operating system provides to allow the processes to manage shared data. Typically, applications can use IPC, categoriz ...
. In fact, message processing exists in many systems, including a kernel-level component of the Mach operating system. The event loop is a specific implementation technique of systems that use
message passing In computer science, message passing is a technique for invoking behavior (i.e., running a program) on a computer. The invoking program sends a message to a process (which may be an actor or object) and relies on that process and its supporting ...
.


Alternative designs

This approach is in contrast to a number of other alternatives: *Traditionally, a program simply ran once, then terminated. This type of program was very common in the early days of computing, and lacked any form of user interactivity. This is still used frequently, particularly in the form of command-line-driven programs. Any parameters are set up in advance and passed in one go when the program starts. *Menu-driven designs. These still may feature a main loop, but are not usually thought of as event driven in the usual sense. Instead, the user is presented with an ever-narrowing set of options until the task they wish to carry out is the only option available. Limited interactivity through the menus is available.


Usage

Due to the predominance of
graphical user interface The GUI ( "UI" by itself is still usually pronounced . or ), graphical user interface, is a form of user interface that allows users to interact with electronic devices through graphical icons and audio indicator such as primary notation, ins ...
s, most modern applications feature a main loop. The get_next_message() routine is typically provided by the operating system, and blocks until a message is available. Thus, the loop is only entered when there is something to process. function main initialize() while message != quit message := get_next_message() process_message(message) end while end function


File interface

Under
Unix Unix (; trademarked as UNIX) is a family of multitasking, multiuser computer operating systems that derive from the original AT&T Unix, whose development started in 1969 at the Bell Labs research center by Ken Thompson, Dennis Ritchie, ...
, the "
everything is a file Everything is a file is an idea that Unix, and its derivatives handle input/output to and from resources such as documents, hard-drives, modems, keyboards, printers and even some inter-process and network communications as simple streams of bytes ...
" paradigm naturally leads to a file-based event loop. Reading from and writing to files, inter-process communication, network communication, and device control are all achieved using file I/O, with the target identified by a
file descriptor In Unix and Unix-like computer operating systems, a file descriptor (FD, less frequently fildes) is a process-unique identifier ( handle) for a file or other input/output resource, such as a pipe or network socket. File descriptors typically ha ...
. The select and poll system calls allow a set of file descriptors to be monitored for a change of state, e.g. when data becomes available to be read. For example, consider a program that reads from a continuously updated file and displays its contents in the
X Window System The X Window System (X11, or simply X) is a windowing system for bitmap displays, common on Unix-like operating systems. X provides the basic framework for a GUI environment: drawing and moving windows on the display device and interacting wi ...
, which communicates with clients over a socket (either Unix domain or Berkeley): def main(): file_fd = open("logfile.log") x_fd = open_display() construct_interface() while True: rlist, _, _ = select.select( ile_fd, x_fd [], []): if file_fd in rlist: data = file_fd.read() append_to_display(data) send_repaint_message() if x_fd in rlist: process_x_messages()


Handling signals

One of the few things in Unix that does not conform to the file interface are asynchronous events ( signals). Signals are received in signal handlers, small, limited pieces of code that run while the rest of the task is suspended; if a signal is received and handled while the task is blocking in select(), select will return early with EINTR; if a signal is received while the task is CPU bound, the task will be suspended between instructions until the signal handler returns. Thus an obvious way to handle signals is for signal handlers to set a global flag and have the event loop check for the flag immediately before and after the select() call; if it is set, handle the signal in the same manner as with events on file descriptors. Unfortunately, this gives rise to a
race condition A race condition or race hazard is the condition of an electronics, software, or other system where the system's substantive behavior is Sequential logic, dependent on the sequence or timing of other uncontrollable events. It becomes a software ...
: if a signal arrives immediately between checking the flag and calling select(), it will not be handled until select() returns for some other reason (for example, being interrupted by a frustrated user). The solution arrived at by
POSIX The Portable Operating System Interface (POSIX) is a family of standards specified by the IEEE Computer Society for maintaining compatibility between operating systems. POSIX defines both the system- and user-level application programming in ...
is the pselect() call, which is similar to select() but takes an additional sigmask parameter, which describes a ''signal mask''. This allows an application to mask signals in the main task, then remove the mask for the duration of the select() call such that signal handlers are only called while the application is I/O bound. However, implementations of pselect() have not always been reliable; versions of Linux prior to 2.6.16 do not have a pselect() system call, forcing
glibc The GNU C Library, commonly known as glibc, is the GNU Project's implementation of the C standard library. Despite its name, it now also directly supports C++ (and, indirectly, other programming languages). It was started in the 1980s ...
to emulate it via a method prone to the very same race condition pselect() is intended to avoid. An alternative, more portable solution, is to convert asynchronous events to file-based events using the '' self-pipe trick'', where "a signal handler writes a byte to a pipe whose other end is monitored by select() in the main program". In
Linux kernel The Linux kernel is a free and open-source, monolithic, modular, multitasking, Unix-like operating system kernel. It was originally authored in 1991 by Linus Torvalds for his i386-based PC, and it was soon adopted as the kernel for the GNU ...
version 2.6.22, a new system call signalfd() was added, which allows receiving signals via a special file descriptor.


Implementations


Windows applications

On the
Microsoft Windows Windows is a group of several proprietary graphical operating system families developed and marketed by Microsoft. Each family caters to a certain sector of the computing industry. For example, Windows NT for consumers, Windows Server for ...
operating system, a process that interacts with the user ''must'' accept and react to incoming messages, which is almost inevitably done by a message loop in that process. In Windows, a message is equated to an event created and imposed upon the operating system. An event can be user interaction, network traffic, system processing, timer activity, inter-process communication, among others. For non-interactive, I/O only events, Windows has I/O completion ports. I/O completion port loops run separately from the Message loop, and do not interact with the Message loop out of the box. The "heart" of most Win32 applications is th
WinMain()
function, which call
GetMessage()
in a loop. GetMessage() blocks until a message, or "event", is received (with functio
PeekMessage()
as a non-blocking alternative). After some optional processing, it will cal
DispatchMessage()
which dispatches the message to the relevant handler, also known as
WindowProc In Win32 application programming, WindowProc (or window procedure) is a user-defined callback function that processes messages sent to a window. This function is specified when an application registers its window class In computer programming, a ...
. Normally, messages that have no specia
WindowProc()
are dispatched to DefWindowProc, the default one. DispatchMessage() calls the WindowProc of the HWND handle of the message (registered with th
RegisterClass()
function).


Message ordering

More recent versions of Microsoft Windows guarantee to the programmer that messages will be delivered to an application's message loop in the order that they were perceived by the system and its peripherals. This guarantee is essential when considering the design consequences of multithreaded applications. However, some messages have different rules, such as messages that are always received last, or messages with a different documented priority.GetMessage() function
with message priority list.


X Window System


Xlib event loop

X applications using Xlib directly are built around the XNextEvent family of functions; XNextEvent blocks until an event appears on the event queue, whereupon the application processes it appropriately. The Xlib event loop only handles window system events; applications that need to be able to wait on other files and devices could construct their own event loop from primitives such as ConnectionNumber, but in practice tend to use multithreading. Very few programs use Xlib directly. In the more common case, GUI toolkits based on Xlib usually support adding events. For example, toolkits based on Xt Intrinsics have XtAppAddInput() and XtAppAddTimeout(). Please note that it is not safe to call Xlib functions from a signal handler, because the X application may have been interrupted in an arbitrary state, e.g. within XNextEvent. Se

for a solution for X11R5, X11R6 and Xt.


GLib event loop

The
GLib GLib is a bundle of three (formerly five) low-level system libraries written in C and developed mainly by GNOME. GLib's code was separated from GTK, so it can be used by software other than GNOME and has been developed in parallel ever s ...
event loop was originally created for use in GTK but is now used in non-GUI applications as well, such as
D-Bus In computing, D-Bus (short for "Desktop Bus") is a message-oriented middleware mechanism that allows communication between multiple processes running concurrently on the same machine. D-Bus was developed as part of the freedesktop.org project ...
. The resource polled is the collection of
file descriptor In Unix and Unix-like computer operating systems, a file descriptor (FD, less frequently fildes) is a process-unique identifier ( handle) for a file or other input/output resource, such as a pipe or network socket. File descriptors typically ha ...
s the application is interested in; the polling block will be interrupted if a signal arrives or a
timeout Time-out, Time Out, or timeout may refer to: Time * Time-out (sport), in various sports, a break in play, called by a team * Television timeout, a break in sporting action so that a commercial break may be taken * Timeout (computing), an enginee ...
expires (e.g. if the application has specified a timeout or idle task). While GLib has built-in support for file descriptor and child termination events, it is possible to add an event source for any event that can be handled in a prepare-check-dispatch mode

Application libraries that are built on the GLib event loop include
GStreamer GStreamer is a pipeline-based multimedia framework that links together a wide variety of media processing systems to complete complex workflows. For instance, GStreamer can be used to build a system that reads files in one format, processes the ...
and the
asynchronous I/O In computer science, asynchronous I/O (also non-sequential I/O) is a form of input/output processing that permits other processing to continue before the transmission has finished. A name used for asynchronous I/O in the Windows API is overlapp ...
methods of GnomeVFS, but GTK remains the most visible client library. Events from the
windowing system In computing, a windowing system (or window system) is software that manages separately different parts of display screens. It is a type of graphical user interface (GUI) which implements the WIMP ( windows, icons, menus, pointer) paradigm f ...
(in X, read off the X
socket Socket may refer to: Mechanics * Socket wrench, a type of wrench that uses separate, removable sockets to fit different sizes of nuts and bolts * Socket head screw, a screw (or bolt) with a cylindrical head containing a socket into which the hexag ...
) are translated by GDK into GTK events and emitted as GLib signals on the application's widget objects.


macOS Core Foundation run loops

Exactly one CFRunLoop is allowed per thread, and arbitrarily many sources and observers can be attached. Sources then communicate with observers through the run loop, with it organising queueing and dispatch of messages. The CFRunLoop is abstracted in
Cocoa Cocoa may refer to: Chocolate * Chocolate * ''Theobroma cacao'', the cocoa tree * Cocoa bean, seed of ''Theobroma cacao'' * Chocolate liquor, or cocoa liquor, pure, liquid chocolate extracted from the cocoa bean, including both cocoa butter an ...
as an NSRunLoop, which allows any message (equivalent to a function call in non-
reflective Reflection is the change in direction of a wavefront at an interface between two different media so that the wavefront returns into the medium from which it originated. Common examples include the reflection of light, sound and water waves. The ' ...
runtimes) to be queued for dispatch to any object.


See also

*
Asynchronous I/O In computer science, asynchronous I/O (also non-sequential I/O) is a form of input/output processing that permits other processing to continue before the transmission has finished. A name used for asynchronous I/O in the Windows API is overlapp ...
* Event-driven programming *
Inter-process communication In computer science, inter-process communication or interprocess communication (IPC) refers specifically to the mechanisms an operating system provides to allow the processes to manage shared data. Typically, applications can use IPC, categoriz ...
*
Message passing In computer science, message passing is a technique for invoking behavior (i.e., running a program) on a computer. The invoking program sends a message to a process (which may be an actor or object) and relies on that process and its supporting ...
*The ''game loop'' in Game programming


References

{{Reflist


External links


Meandering Through the Maze of MFC Message and Command RoutingUsing Messages and Message Queues (MSDN)Using Window Procedures (MSDN)WindowProc (MSDN)
Control flow Events (computing)