Event-Driven Programming

Your first programs probably ran from top to bottom: read some input, compute, print a result, stop. A program with buttons, timers or network connections often needs a different structure, because it cannot know whether the next thing to happen will be a click, a key press or an arriving message. Event-driven programming is a style in which events (user actions, timer expirations, messages from other programs) determine which code runs next rather than one fixed sequence of operations. You meet it whenever you write a GUI, a game, a script for a web page or a network server.

Control-driven versus event-driven flow

In a simple control-driven, sequential program, your code decides when input happens. A line such as name = input() waits until the user types something, and execution then continues with the next statement. The order of operations is written into the source. This comparison concerns program flow: procedural programming can be used in both sequential and event-driven programs.


An event-driven program inverts that relationship. Instead of asking for input at fixed points, you write an event handler, a function that runs when a matching event is dispatched, and register it with the object that produces the event. The handler is a callback: you hand it over during setup, and the system calls it later.


For the examples below, we use a simplified single-threaded model with one queue that dispatches events in arrival order.


Feature

Simple sequential flow

Event-driven model used here

What decides the next step

The program's own statements

The oldest queued event selects its handlers

Waiting for input

At points the code chooses

The loop waits when its queue is empty

Typical structure

One main sequence of steps

Setup, handler registration, then an event loop

Typical uses

Batch jobs, calculations

GUIs, games, web pages, servers


Neither style is better in general. A file converter runs well as a sequence; a text editor that must react to different inputs fits the event model.

The event loop

In this lesson's model, events enter one FIFO queue. The event loop repeatedly waits for an event, takes the oldest one, calls its registered handlers and returns to the queue. These are teaching assumptions, not requirements of all event-driven systems. Real systems can use multiple queues, scheduling priorities or other dispatch mechanisms.


The following Python-like pseudocode represents only our simplified model. The registration lookup uses both the event source and its type:


Python
while True:
    event = queue.get()                 # waits while the queue is empty
    key = (event.source, event.type)
    for handler in handlers.get(key, []):
        handler(event)                  # runs to completion


In this model, a handler runs to completion before the next event is dispatched. Events arriving meanwhile wait in the queue. An event with no registered handler is removed and ignored.


A diagram shows event sources feeding a queue of waiting events, the queue feeding the event loop, the loop calling handlers, and an arrow returning from the handlers to the loop.


Example: A Save handler blocks the loop for 300 ms. A key event arrives 100 ms after it starts. Assuming no other queued events and negligible dispatch overhead, the key event waits for the remaining 300−100=200300 - 100 = 200 ms before its handler begins.



Registering handlers

Registration connects three things: an event source (a button, timer or network socket), an event type (click, tick or data received) and the handler. In many libraries it looks like button.on_click(save). You pass the function save itself. Writing button.on_click(save()) calls save during setup and registers whatever it returns, a common bug.


In our FIFO model, events are dispatched in queue arrival order, not in the order their handlers appear in the source. One event may have several handlers; their order follows the registration system's rules. One handler may also serve several sources.



What to remember

  • Simple sequential code specifies an operation sequence; event-driven code selects responses to events.
  • An event handler is a callback registered for an event type on a source; register the function, do not call it.
  • In this lesson's single-threaded FIFO model, the loop dispatches queued events in arrival order. Other systems may schedule them differently.
  • Each handler in this model runs to completion. Keep work on the loop short; a timer alone does not prevent blocking.

Example: Tracing a single-threaded event loop

A puzzle game keeps an integer variable score, which starts at 0. During setup it registers three handlers on a single-threaded event loop with a FIFO queue:


Event

Handler action

Handler run time

Click

add 3 to score

20 ms

Key D

double score

10 ms

Timer tick

subtract 1 from score

5 ms


Five events then arrive: a click at 0 ms, Key D at 5 ms, a click at 8 ms, a timer tick at 12 ms and Key D at 40 ms. The loop is idle at 0 ms, and dispatch overhead is negligible. The response time of an event is the time from its arrival until its handler finishes.


a) Find the value of score after all five handlers have run.


The handlers run one at a time in the order their events arrive, not in the order they were registered. Track score through the queue.


After the first click, score is ________. Key D doubles it to ________, the second click raises it to ________ and the timer tick lowers it to ________. The final Key D doubles that value:


score=2×8=16\text{score} = 2 \times 8 = 16


The final value of score is 16.


b) Find the response time of the timer tick.


A handler starts at the later of two times: when its event arrives, and when the previous handler finishes. An event that arrives while a handler is running waits in the queue.


The first click runs from 0 ms until ________. Key D arrived at 5 ms, so it waits and runs from 20 ms to ________. The second click runs from 30 ms to ________. The timer tick, waiting since 12 ms, starts at 50 ms and finishes at ________.


tresponse=tfinish−tarrive=55 ms−12 ms=43 mst_{\text{response}} = t_{\text{finish}} - t_{\text{arrive}} = 55\ \text{ms} - 12\ \text{ms} = 43\ \text{ms}


The timer tick's response time is 43 ms: 38 ms waiting in the queue and 5 ms executing its handler.


c) The developer moves the slow part of the click handler off the event loop, so each click handler now runs for 4 ms. Find the new response time of the timer tick, and state whether the final value of score changes.


Recompute the schedule with 4 ms clicks. The first click runs from 0 ms to ________. The loop is idle until Key D arrives at 5 ms, and Key D runs from 5 ms to ________. The second click runs from 15 ms to ________. The timer tick then runs from 19 ms to 24 ms.


tresponse=24 ms−12 ms=12 mst_{\text{response}} = 24\ \text{ms} - 12\ \text{ms} = 12\ \text{ms}


The final Key D arrives at 40 ms, when the loop is idle, so it runs from 40 ms to 50 ms. The events are still handled in the same order, so score again finishes at 16; only the timing changed. The timer tick's response time drops from 43 ms to 12 ms, which is why handlers should be kept short.

Match each term from event-driven programming with the description that fits it. Each description is used exactly once.

Match each term
A.

A first-in, first-out buffer of occurrences waiting to be processed

B.

Checking a device or flag over and over to see whether its state has changed

C.

Code that repeatedly waits for the next pending occurrence and dispatches it

D.

A record that something happened, such as a mouse click, a key press or a timer expiring

E.

A function that runs in response to one particular kind of occurrence

F.

Associating a function with a source and a type of occurrence so the system calls it later

Event queue

Event handler

Listener registration

Polling

Event

Event loop

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A user clicks a Save button while the single-threaded event loop of a desktop program is still running the handler for an earlier key press. No other events are waiting. Put these stages in the order they happen, from the click until the loop is ready for another event.

Loading ordering steps…

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A drawing app runs all of its handlers on one single-threaded event loop, and its redraw handler must run 50 times per second for the window to look smooth. That gives each gap between two redraws a time budget of ms, and every other handler that runs in that gap must fit inside it. A filter handler that runs for 340 ms without returning is said to the event loop, and the time it holds up redraws spans of those redraw intervals, during which the window appears frozen.

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Extra Practice