C++ Advanced · Lesson 03 of 23
Event-driven programming
An event loop, dispatching events to handlers, and never blocking inside a handler.
Estimated time · 60–90 min
Learning goals
What you will understand
- Explain event-driven programming in your own words
- Use it in a small robotics example
- Verify the result instead of assuming it worked
Understand the idea first
The mental model
Event-driven programs do not run top to bottom; they wait for events (a message arrived, a timer fired, a goal was requested) and run the matching handler. A loop takes the next event and dispatches it. ROS 2's rclcpp::spin is exactly this loop.
Handlers must be short. A handler that blocks or waits for another event stops every other handler from running, so long work belongs on another thread or in a state machine advanced by later events.
Guided lesson
Work through these steps
- 1.
Read the event-driven programming example and identify what each line owns or changes.
- 2.
Create a small source file, compile with -std=c++17 and warnings enabled, and run it.
- 3.
Change one input, predict the result before running, then compare the output.
- 4.
Record one compiler or runtime error and explain the correction in your own words.
Worked example
Read it before you run it
struct Event { std::string type; double value; };
// An event: what happened and a number.
class EventLoop {
// A tiny dispatcher.
public:
// Public interface.
using Handler = std::function<void(const Event&)>;
// A handler takes an event.
void on(const std::string& type, Handler h) { handlers_[type] = std::move(h); }
// Register one handler per event type.
void post(Event e) { queue_.push(std::move(e)); }
// Add an event to the waiting queue.
void run_pending() {
// Process everything queued so far.
while (!queue_.empty()) {
// Until the queue is empty...
Event e = std::move(queue_.front()); queue_.pop();
// Take the oldest event.
if (auto it = handlers_.find(e.type); it != handlers_.end()) it->second(e);
// Dispatch it to its handler, if one is registered.
}
// End of the while loop.
}
// End of run_pending.
private:
// Hidden state.
std::map<std::string, Handler> handlers_; std::queue<Event> queue_;
// Handlers by type and the queue of waiting events.
};
// End of the class.What the example is doing
- 1.Read declarations from right to left: identify each value's type, name, and initial value.
- 2.Follow the data through each expression before considering syntax shortcuts.
- 3.Compile with warnings enabled; a clean build is part of the result, not an optional polish step.
Watch it run · Messages between nodes
See what this code does
The terminal types this lesson's practice solution and runs it. The scene shows the kind of robot behaviour that code drives. It plays by itself and loops.
Demo for Event-driven programming. Expected result: temp 42 fault 1
Practice code
Now type it yourself
Copy the starter into practice.cpp and replace every TODO with your own code. Build and run it: g++ -std=c++17 -Wall -Wextra -Wpedantic practice.cpp -o practice -pthread && ./practice
#include <functional>
#include <iostream>
#include <map>
#include <queue>
#include <string>
struct Event {
std::string type;
double value;
};
class EventLoop {
public:
using Handler = std::function<void(const Event&)>;
void on(const std::string& type, Handler h) { handlers_[type] = std::move(h); }
void post(Event e) { queue_.push(std::move(e)); }
void run_pending() {
// TODO: while the queue is not empty: take the oldest event, pop it, and call its handler if one exists
}
private:
std::map<std::string, Handler> handlers_;
std::queue<Event> queue_;
};
int main() {
EventLoop loop;
loop.on("temperature", [](const Event& e) { std::cout << "temp " << e.value << '\n'; });
loop.on("fault", [](const Event& e) { std::cout << "fault " << e.value << '\n'; });
loop.post({"temperature", 42});
loop.post({"fault", 1});
loop.run_pending();
return 0;
}Expected output
temp 42
fault 1Stuck? Show the full solution (try it yourself first)
#include <functional>
#include <iostream>
#include <map>
#include <queue>
#include <string>
struct Event {
std::string type;
double value;
};
class EventLoop {
public:
using Handler = std::function<void(const Event&)>;
void on(const std::string& type, Handler h) { handlers_[type] = std::move(h); }
void post(Event e) { queue_.push(std::move(e)); }
void run_pending() {
while (!queue_.empty()) {
Event e = std::move(queue_.front());
queue_.pop();
if (auto it = handlers_.find(e.type); it != handlers_.end()) it->second(e);
}
}
private:
std::map<std::string, Handler> handlers_;
std::queue<Event> queue_;
};
int main() {
EventLoop loop;
loop.on("temperature", [](const Event& e) { std::cout << "temp " << e.value << '\n'; });
loop.on("fault", [](const Event& e) { std::cout << "fault " << e.value << '\n'; });
loop.post({"temperature", 42});
loop.post({"fault", 1});
loop.run_pending();
return 0;
}Expected result
How you know it worked
- After adding the shown fragment to the guided exercise with its listed headers and surrounding program, the finished program builds with -Wall -Wextra -Wpedantic.
- Changing the stated input produces the result you predicted.
Practical exercise
Apply the lesson
Register handlers for 'temperature' and 'fault' on the loop, post five events, and print what each handler receives. Add a handler that posts a new event and confirm it runs in the same run_pending() call.
Before you continue
- The program builds with -std=c++17 and no warnings
- You can explain the key rule without reading the example
- The normal and edge cases both have recorded results
If something goes wrong
Start at the first error. Check spelling, required #include lines, and whether the declaration appears before use.
Print the inputs and intermediate values, then check conversions, units, and collection order.