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 A design pattern is the re-usable form of a solution to a design problem. The idea was introduced by the architect Christopher Alexander and has been adapted for various other disciplines, particularly software engineering. The " Gang of Four" b ...
that waits for and dispatches
events Event may refer to: Gatherings of people * Ceremony, an event of ritual significance, performed on a special occasion * Convention (meeting), a gathering of individuals engaged in some common interest * Event management, the organization of ev ...
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 * Progra ...
. 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 In programming and software design, an event is an action or occurrence recognized by software, often originating asynchronously from the external environment, that may be handled by the software. Computer events can be generated or triggered ...
("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 Poll, polled, or polling may refer to: Figurative head counts * Poll, a formal election ** Election verification exit poll, a survey taken to verify election counts ** Polling, voting to make decisions or determine opinions ** Polling places o ...
). 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 ''imper ...
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 In computer science, message queues and mailboxes are software-engineering components typically used for inter-process communication (IPC), or for inter- thread communication within the same process. They use a queue for messaging – the ...
(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, categori ...
. 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 i ...
.


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 A parameter (), generally, is any characteristic that can help in defining or classifying a particular system (meaning an event, project, object, situation, etc.). That is, a parameter is an element of a system that is useful, or critical, when ...
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, inste ...
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, and ot ...
, 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 byte ...
" 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 have ...
. The select and
poll Poll, polled, or polling may refer to: Figurative head counts * Poll, a formal election ** Election verification exit poll, a survey taken to verify election counts ** Polling, voting to make decisions or determine opinions ** Polling places o ...
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 wit ...
, which communicates with clients over a socket (either Unix domain or
Berkeley Berkeley most often refers to: *Berkeley, California, a city in the United States **University of California, Berkeley, a public university in Berkeley, California * George Berkeley (1685–1753), Anglo-Irish philosopher Berkeley may also refer ...
): 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 In signal processing, a signal is a function that conveys information about a phenomenon. Any quantity that can vary over space or time can be used as a signal to share messages between observers. The ''IEEE Transactions on Signal Processing'' ...
). Signals are received in
signal handler Signals are standardized messages sent to a running program to trigger specific behavior, such as quitting or error handling. They are a limited form of inter-process communication (IPC), typically used in Unix, Unix-like, and other POSIX-compli ...
s, 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 {{Unreferenced, date=April 2007 In computer science, a computer is CPU-bound (or compute-bound) when the time for it to complete a task is determined principally by the speed of the central processor: processor utilization is high, perhaps at 100% ...
, 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 dependent on the sequence or timing of other uncontrollable events. It becomes a bug when one or more of t ...
: 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 interf ...
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 In computer science, I/O bound refers to a condition in which the time it takes to complete a computation is determined principally by the period spent waiting for input/output operations to be completed. This is the opposite of a task being CPU bo ...
. 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 by ...
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 ope ...
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 serv ...
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 computer science, the event loop is a programming construct or design pattern that waits for and dispatches events or messages in a program. The event loop works by making a request to some internal or external "event provider" (that generally ...
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 The Windows API, informally WinAPI, is Microsoft's core set of application programming interfaces (APIs) available in the Microsoft Windows operating systems. The name Windows API collectively refers to several different platform implementations th ...
applications Application may refer to: Mathematics and computing * Application software, computer software designed to help the user to perform specific tasks ** Application layer, an abstraction layer that specifies protocols and interface methods used in a c ...
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. Normally, messages that have no specia
WindowProc()
are dispatched to DefWindowProc, the default one. DispatchMessage() calls the WindowProc of the
HWND In computer programming, a handle is an abstract reference to a resource that is used when application software references blocks of memory or objects that are managed by another system like a database or an operating system. A resource handle ...
handle A handle is a part of, or attachment to, an object that allows it to be grasped and manipulated by hand. The design of each type of handle involves substantial ergonomic issues, even where these are dealt with intuitively or by following tra ...
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 Xlib (also known as libX11) is an X Window System protocol client library written in the C programming language. It contains functions for interacting with an X server. These functions allow programmers to write programs without knowing the ...
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 sinc ...
event loop was originally created for use in
GTK GTK (formerly GIMP ToolKit and GTK+) is a free and open-source cross-platform widget toolkit for creating graphical user interfaces (GUIs). It is licensed under the terms of the GNU Lesser General Public License, allowing both free and propriet ...
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 have ...
s the application is interested in; the polling block will be interrupted if a
signal In signal processing, a signal is a function that conveys information about a phenomenon. Any quantity that can vary over space or time can be used as a signal to share messages between observers. The ''IEEE Transactions on Signal Processing'' ...
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 them, ...
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 overlappe ...
methods of
GnomeVFS GnomeVFS (short for GNOME Virtual File System) was an abstraction layer of the GNOME platform for the reading, writing and execution of files. Before GNOME 2.22 GnomeVFS was primarily used by the appropriate versions of Nautilus file manager (rena ...
, but
GTK GTK (formerly GIMP ToolKit and GTK+) is a free and open-source cross-platform widget toolkit for creating graphical user interfaces (GUIs). It is licensed under the terms of the GNU Lesser General Public License, allowing both free and propriet ...
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 for ...
(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 GDK ( GIMP Drawing Kit) is a library that acts as a wrapper around the low-level functions provided by the underlying windowing and graphics systems. GDK lies between the display server and the GTK library, handling basic rendering such as dr ...
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 and ...
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 overlappe ...
*
Event-driven programming In computer programming, event-driven programming is a programming paradigm in which the flow of the program is determined by events such as user actions ( mouse clicks, key presses), sensor outputs, or message passing from other programs or t ...
*
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, categori ...
*
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 i ...
*The ''game loop'' in
Game programming Game programming, a subset of game development, is the software development of video games. Game programming requires substantial skill in software engineering and computer programming in a given language, as well as specialization in one or mor ...


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)