ArticleslgStudy

computer science

Event loop

Event loop is a computer science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Event loop rather than just read about it. In short: In software, an event loop is an algorithm that continually dispatches control flow for events. The loop requests the next event from an event provider (which generally blocks the loop until an event occurs), and when an event is received, invokes its associated event handler.

Key takeaways

  • Event loop belongs to computer science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Event loop to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Event loop from memory before moving on to harder problems.

Reference excerpt

In software, an event loop is an algorithm that continually dispatches control flow for events. The loop requests the next event from an event provider (which generally blocks the loop until an event occurs), and when an event is received, invokes its associated event handler. When the event loop is the central event dispatcher of a program, as it often is, it is called the main loop or main event loop. In modern environments such as web browsers and server runtimes, the event loop is a fundamental mechanism that enables asynchronous execution by continuously monitoring and dispatching events or messages from a queue when the main program thread is idle. In JavaScript, the event loop allows non-blocking handling of tasks such as user interactions, timers, and I/O operations despite the language being single-threaded. The same algorithm can be used to process inbound messages, a superset of events. In this context, the algorithm is called a message loop, message dispatcher, or message pump. A common use for a message loop is message passing inter-process communication where the message queue is maintained outside of the program (such as by the operating system). Typically, a program that operates in a graphical user interface (GUI) environment uses an event loop, and due to the predominance of GUI environments, most modern applications have a main event loop. In the following pseudocode, get_next_message() is a placeholder for a function that is typically provided by the operating system that blocks until a message is available. Thus, the loop only repeats when there is a message to process.

loop message := get_next_message() process_message(message) while message != quit

Alternatives Many programs include an event loop in the high-level design; a main event loop, but there are alternative designs. A program can exit as soon as it completes the actions that it's designed to do without external (i.e. user) interaction. Often, such a program has optional behavior that is set up before the program starts such as via the command-line interface (CLI) or environment variables. Utility software is often of this nature. Even if a program provides for user interaction, it might not use an event loop. A program that provides an internal CLI does include a command processor that is similar to an event loop in that it dispatches to command handlers based on user input.

Examples

HTML/JavaScript A web page and its JavaScript typically run in a single-threaded web browser process. The browser process deals with messages from a queue one at a time. A JavaScript function or another browser event might be associated with a given message. When the browser process has finished with a message, it proceeds to the next message in the queue. In JavaScript environments, the event loop works with separate queues — including a task queue and a microtask queue — to manage asynchronous operations such as timers, promise callbacks, and DOM events. When the call stack is empty, the event loop selects the next task from these queues to execute.

Windows applications In Windows, 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 the WinMain() function, which calls GetMessage() in a loop. GetMessage() blocks until a message (event), is received (with function PeekMessage() as a non-blocking alternative). After some optional processing, it will call DispatchMessage(), which dispatches the message to the relevant handler, also known as WindowProc. Normally, messages that have no special WindowProc() are dispatched to DefWindowProc, the default one. DispatchMessage() calls the WindowProc of the HWND handle of the message (registered with the RegisterClass() function). More recent versions of Windows guarantee 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.

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(). 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. See [1] for a solution for X11R5, X11R6 and Xt.

GLib event loop The GLib event loop was originally created for use in GTK but is now used in non-GUI applications as well, such as D-Bus. The resource polled is the collection of file descriptors the application is interested in; the polling block will be interrupted if a signal arrives or a timeout 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 model.[2] Application libraries that are built on the GLib event loop include GStreamer and the asynchronous I/O methods of GnomeVFS, but GTK remains the most visible client library. Events from the windowing system (in X, read off the X socket) are translated by GDK into GTK events and emitted as GLib signals on the application's widget objects.

… excerpt ends here. Continue reading the full article.

Worked examples

Example 1 — a first encounter with Event loop

Start with the simplest possible case. Write down what Event loop claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In computer science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Event loop before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Event loop ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Event loop

In research
Event loop appears in computer science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Event loop in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Event loop is common in secondary-school and first-year university syllabi. It links to neighbouring topics Control flow, Events (computing), so understanding it makes those chapters shorter.
In everyday life
Look for Event loop outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.
Ask Teacher Smith questions about this articleOpens your AI tutor with a question about “Event loop” →

How to study Event loop in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Event loop means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Event loop out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Event loop in simple terms?

In software, an event loop is an algorithm that continually dispatches control flow for events. The loop requests the next event from an event provider (which generally blocks the loop until an event occurs), and when an event is received, invokes its associated event handler.

Why does Event loop matter?

Because it connects several computer science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Event loop?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Event loop.

Tags

  • Control flow
  • Events (computing)

Keep exploring