Event-Driven Programming

Table of Contents
Share on:
Share on reddit
Share on linkedin
Share on twitter
Share on email
Embedded systems need a program structure that can respond to a multitude of possible event sequences, any of which can arrive at unpredictable times. This program structure is generally called event-driven programming.

The Hollywood Principle

Most modern event-driven systems are structured according to the Hollywood Principle, which means “Don’t call us, we’ll call you.” So an event-driven program is not in control while waiting for an event; in fact, it’s not even active. Only once the event arrives, the program is called to process the event and then it quickly relinquishes the control again. This arrangement allows an event-driven system to wait for many events in parallel, so the system remains responsive to all events it needs to handle.

Event Loop & Inversion of Control

Event-driven systems are naturally divided into the application, which actually handles the events, and the supervisory event-driven infrastructure (framework), which generically waits for events and dispatches them to the application.

The event-driven infrastructure is typically organized as an event-loop also known as “message loop” or “message pump”:

while (1) { /* "event-loop" (infrastructure) */
    Event *e = getEvent();  /* BLOCKING */
    dispatch(e); /* NO-BLOCKING (application) */

The event-loop is the only place where the program waits (blocks) for events. The event-driven application is not allowed to block, because it must quickly return control after handling each event back to the event loop.

The control resides in the event-driven infrastructure, so from the application standpoint the control is inverted compared to sequential programs, such as threads in a traditional RTOS.

This is the key characteristic of all event-driven systems and is the essence of event-driven programming. The inversion of control is really what it means that “events drive the application” and not the other way around.

Paradigm Shift

Inversion of control and the no-blocking restriction are the defining characteristic of Event-Driven Programming and require a distinctly different way of thinking than the traditional sequential programs, such as “superloops” or threads in a traditional RTOS.
Paradigm sifht: Blocking to Non-Blocking