Lab 3: Cooperative Reactor Loop: Priority Events, LIFO Filters & Monotonic Timers
Eliminate dangling lambda slot crashes with 4-argument context-bound PMF connections, master synchronous sendEvent versus heap-queued postEvent compression and LIFO eventFilter interception, and schedule drift-free CLOCK_MONOTONIC timers without starving QPaintEvent.
Prerequisites in this module
What ./check.sh verifies
- Builds libcore.a and lab_cli cleanly with -std=c++20 -Wall -Wextra -Werror -pedantic.
- Fix compiler warnings or errors in files/core.cpp.
- Archives core.o into libcore.a and links independent TAP verifier.
- Preserve public declarations in files/core.hpp so tests.cpp links.
step 1/15 · inspect starter files and specification
Industrial HMIs fail intermittent soak tests when a safety eventFilter runs in the wrong order, periodic polling timers drift away from sensor frames using now + period, or a delayed singleShot callback fires onto a closed modal popup. In this studio you repair all three mechanisms inside hmi::ReactorLoop.
learner@ksa:~/gl-q01/lab-m03ls -lastarter/Makefilestarter/cli.cppstarter/core.cppstarter/core.hpplearner@ksa:~/gl-q01/lab-m03starter: starter/Makefile
learner@ksa:~/gl-q01/lab-m03$ bat starter/Makefile File: starter/Makefile CC_BIN = g++ AR = ar CFLAGS_ALL = -std=c++20 -Wall -Wextra -Werror -pedantic -O2 LDLIBS = all: libcore.a lab_cli libcore.a: core.o $(AR) rcs $@ $^ lab_cli: cli.o libcore.a $(CC_BIN) $(CFLAGS_ALL) cli.o libcore.a $(LDLIBS) -o $@ %.o: %.cpp core.hpp $(CC_BIN) $(CFLAGS_ALL) -c $< -o $@ .PHONY: all clean clean: rm -f core.o cli.o libcore.a lab_clistarter: starter/cli.cpp
learner@ksa:~/gl-q01/lab-m03$ bat starter/cli.cpp File: starter/cli.cpp #include "core.hpp" #include <algorithm> #include <array> #include <cstdint> #include <cstdio> #include <cstring> #include <ctime> #include <memory> static std::uint64_t now_ns() noexcept { timespec ts{}; clock_gettime(CLOCK_MONOTONIC, &ts); return static_cast<std::uint64_t>(ts.tv_sec) * 1000000000ULL + static_cast<std::uint64_t>(ts.tv_nsec); } static int run_bench() { constexpr int kWarmup = 5; constexpr int kSamples = 40; constexpr int kInner = 200; std::array<std::uint64_t, kSamples> ns{}; volatile std::size_t sink = 0; for (int w = 0; w < kWarmup + kSamples; ++w) { hmi::ReactorLoop loop; hmi::EventTarget panel; std::uint64_t virt_clock = 0; loop.start_timer(0, 10, false, &panel, [&] (std::uint64_t) { loop.post_event(&panel, std::make_unique<hmi::LoopEvent>( hmi::LoopEvent{hmi::EventKind::UpdateRequest, 0}), -1); }); const std::uint64_t t0 = now_ns(); for (int i = 0; i < kInner; ++i) { virt_clock += 10; loop.post_event(&panel, std::make_unique<hmi::LoopEvent>( hmi::LoopEvent{hmi::EventKind::UpdateRequest, 0}), -1); sink += loop.step(virt_clock); } const std::uint64_t dt = (now_ns() - t0) / static_cast<std::uint64_t>(kInner); if (w >= kWarmup) { ns[static_cast<std::size_t>(w - kWarmup)] = dt; } sink += static_cast<std::size_t>(panel.paint_passes); } std::sort(ns.begin(), ns.end()); std::printf("BENCH lab_m03_event_loop_timers clock=CLOCK_MONOTONIC " "benchmark_samples=40 warmup=5 p50_ns=%llu p95_ns=%llu p99_ns=%llu sink=%zu\n", static_cast<unsigned long long>(ns[20]), static_cast<unsigned long long>(ns[38]), static_cast<unsigned long long>(ns[39]), static_cast<std::size_t>(sink)); return 0; } int main(int argc, char **argv) { if (argc > 1 && std::strcmp(argv[1], "--bench") == 0) { return run_bench(); } hmi::ReactorLoop loop; hmi::EventTarget w; int ticks = 0; loop.start_timer(0, 20, false, &w, [&] (std::uint64_t) { ++ticks; }); loop.post_event(&w, std::make_unique<hmi::LoopEvent>(hmi::LoopEvent{hmi::EventKind::UpdateRequest, 0}), -1); loop.post_event(&w, std::make_unique<hmi::LoopEvent>(hmi::LoopEvent{hmi::EventKind::UpdateRequest, 0}), -1); const std::size_t work = loop.step(21); std::printf("coarse_50ms_us=%llu ticks=%d paints=%d work=%zu\n", static_cast<unsigned long long>( hmi::coarse_tolerance_ns(50000000ULL, hmi::TimerKind::Coarse) / 1000ULL), ticks, w.paint_passes, work); return (ticks == 1 && w.paint_passes == 1 && work == 2) ? 0 : 1; }starter: starter/core.cpp
learner@ksa:~/gl-q01/lab-m03$ bat starter/core.cpp File: starter/core.cpp #include "core.hpp" #include <algorithm> namespace hmi { std::uint64_t coarse_tolerance_ns(std::uint64_t period_ns, TimerKind kind) noexcept { return (kind == TimerKind::Coarse) ? (period_ns / 20ULL) : 0ULL; } void EventTarget::install_filter(EventTarget *watcher) { if (!watcher || watcher == this) { return; } m_filters.erase(std::remove(m_filters.begin(), m_filters.end(), watcher), m_filters.end()); m_filters.push_back(watcher); } bool EventTarget::event_filter(EventTarget *, LoopEvent *) { return false; } bool EventTarget::on_event(LoopEvent *ev) { if (ev->kind == EventKind::KeyPress) { ++handled_keys; trace.push_back(ev->code); return true; } if (ev->kind == EventKind::UpdateRequest) { ++paint_passes; return true; } trace.push_back(ev->code); return true; } bool ReactorLoop::send_event(EventTarget *dst, LoopEvent *ev) { if (!dst || !ev) { return false; } const auto &flts = dst->filters(); for (auto it = flts.begin(); it != flts.end(); ++it) { /* BUG: FIFO instead of LIFO filter order */ if ((*it)->event_filter(dst, ev)) { return true; } } return dst->on_event(ev); } void ReactorLoop::post_event(EventTarget *dst, std::unique_ptr<LoopEvent> ev, int priority) { if (!dst || !ev) { return; } if (ev->kind == EventKind::UpdateRequest) { for (const auto &q : m_queue) { if (q.dst == dst && q.ev->kind == EventKind::UpdateRequest) { return; } } } m_queue.push_back({priority, m_seq++, dst, std::move(ev)}); } int ReactorLoop::start_timer(std::uint64_t now_ns, std::uint64_t period_ns, bool single_shot, const EventTarget *context, std::function<void(std::uint64_t)> cb) { const int id = m_next_timer++; m_timers.push_back({id, now_ns + period_ns, period_ns, single_shot, true, context != nullptr, context ? context->life_token() : std::weak_ptr<bool>{}, std::move(cb)}); return id; } bool ReactorLoop::cancel_timer(int timer_id) noexcept { for (auto &t : m_timers) { if (t.id == timer_id && t.active) { t.active = false; return true; } } return false; } std::size_t ReactorLoop::step(std::uint64_t now_ns) { std::size_t work = 0; for (;;) { TimerEntry *due = nullptr; for (auto &t : m_timers) { if (!t.active || t.deadline_ns > now_ns) { continue; } if (!due || t.deadline_ns < due->deadline_ns || (t.deadline_ns == due->deadline_ns && t.id < due->id)) { due = &t; } } if (!due) { break; } /* BUG: ignores expired context life_token, firing timer on destroyed EventTarget! */ const std::uint64_t sched = due->deadline_ns; if (due->single_shot || due->period_ns == 0) { due->active = false; } else { due->deadline_ns = now_ns + due->period_ns; /* BUG: cumulative wakeup drift instead of phase lock */ } due->cb(sched); ++work; } std::sort(m_queue.begin(), m_queue.end(), [] (const Queued &a, const Queued &b) { if (a.priority != b.priority) { return a.priority > b.priority; } return a.seq < b.seq; }); while (!m_queue.empty()) { Queued item = std::move(m_queue.front()); m_queue.erase(m_queue.begin()); send_event(item.dst, item.ev.get()); ++work; } return work; } } // namespace hmistarter: starter/core.hpp
learner@ksa:~/gl-q01/lab-m03$ bat starter/core.hpp File: starter/core.hpp #pragma once #include <cstddef> #include <cstdint> #include <functional> #include <memory> #include <vector> namespace hmi { enum class EventKind { KeyPress, UpdateRequest, Custom }; enum class TimerKind { Precise, Coarse }; struct LoopEvent { EventKind kind; int code = 0; }; class EventTarget { public: EventTarget() : m_alive(std::make_shared<bool>(true)) {} virtual ~EventTarget() { *m_alive = false; } EventTarget(const EventTarget &) = delete; EventTarget &operator=(const EventTarget &) = delete; std::weak_ptr<bool> life_token() const noexcept { return m_alive; } void install_filter(EventTarget *watcher); virtual bool event_filter(EventTarget *watched, LoopEvent *ev); virtual bool on_event(LoopEvent *ev); const std::vector<EventTarget *> &filters() const noexcept { return m_filters; } int handled_keys = 0; int paint_passes = 0; std::vector<int> trace; private: std::shared_ptr<bool> m_alive; std::vector<EventTarget *> m_filters; }; std::uint64_t coarse_tolerance_ns(std::uint64_t period_ns, TimerKind kind) noexcept; class ReactorLoop { public: static bool send_event(EventTarget *dst, LoopEvent *ev); void post_event(EventTarget *dst, std::unique_ptr<LoopEvent> ev, int priority = 0); int start_timer(std::uint64_t now_ns, std::uint64_t period_ns, bool single_shot, const EventTarget *context, std::function<void(std::uint64_t)> cb); bool cancel_timer(int timer_id) noexcept; std::size_t step(std::uint64_t now_ns); private: struct Queued { int priority; std::size_t seq; EventTarget *dst; std::unique_ptr<LoopEvent> ev; }; struct TimerEntry { int id; std::uint64_t deadline_ns; std::uint64_t period_ns; bool single_shot; bool active; bool has_ctx; std::weak_ptr<bool> ctx; std::function<void(std::uint64_t)> cb; }; std::size_t m_seq = 0; int m_next_timer = 1; std::vector<Queued> m_queue; std::vector<TimerEntry> m_timers; }; } // namespace hmistep 2/15 · 2. learning objectives
- Dispatch installed
EventTargetfilters in LIFO order (rbegin()torend()) while compressing duplicateUpdateRequestposts. - Maintain zero-drift phase alignment (
deadline_ns += period_ns) with stale-interval skip-ahead and exact5%TimerKind::Coarsemath. - Check
EventTarget::life_token()before firing context-bound timers so destroyed receivers never experience use-after-free.
step 3/15 · 3. environment requirements
All automated verification steps run in unprivileged user space on a POSIX Linux host using g++ -std=c++20 -Wall -Wextra -Werror -pedantic and clock_gettime(CLOCK_MONOTONIC). Recorded transcripts in captures.json were generated on x86_64 running kernel 7.0.0-42-generic and prove protocol, state-machine, and memory invariants only. Physical bus timing, DMA cache coherency, and board peripheral behavior require target validation on Linux kernel 6.12 LTS (ARMv7-A Cortex-A7).
step 4/15 · 4. required software and hardware
- Host workstation:
g++(-std=c++20 -Wall -Wextra -Werror -pedantic), GNUmake,ar(binutils), and POSIX/bin/sh. - Target environment (optional hardware step, Section 13):
ARMv7-ACortex-A7panel runningLinux kernel6.12 LTS and Qt 6.8 to measure realQElapsedTimerQt::PreciseTimerjitter understress-ngCPU load and WaylandQPaintEventcommits.
step 5/15 · 5. complete executable commands
learner@ksa:~/gl-q01/lab-m03$ bat script.sh File: script.sh make -B -C files ./files/lab_cli ./files/lab_cli --bench sh check.shstep 6/15 · 6. annotated source code
files/core.cpp enforces the production invariants that starter/core.cpp breaks:
learner@ksa:~/gl-q01/lab-m03$ bat example.cpp File: example.cpp if (due->has_ctx) { auto sp = due->ctx.lock(); if (!sp || !*sp) { due->active = false; // Receiver died; cancel callback cleanly! continue; } } const std::uint64_t sched = due->deadline_ns; if (due->single_shot || due->period_ns == 0) { due->active = false; } else { do { due->deadline_ns += due->period_ns; // Phase-locked + stale skip! } while (due->deadline_ns <= now_ns); }starter/core.cpp contains three classic reactor bugs: (1) ReactorLoop::send_event() iterates flts.begin()..flts.end() (FIFO) instead of rbegin()..rend() (LIFO); (2) ReactorLoop::step() computes due->deadline_ns = now_ns + due->period_ns, accumulating wakeup jitter; and (3) step() skips checking due->ctx.lock(), invoking callbacks after ~EventTarget().
step 7/15 · 7. expected output
Passing files/ run (sh check.sh, exit code 0):
learner@ksa:~/gl-q01/lab-m03$ bat listing.txt File: listing.txt TAP version 13 1..5 ok 1 - builds libcore.a and lab_cli cleanly with -std=c++20 -Wall -Wextra -Werror -pedantic ok 2 - archives core.o into libcore.a and links independent TAP verifier ok 3 - drains priority events, coalesces UpdateRequest, and runs event_filter in LIFO order ok 4 - computes 5ok 5 - auto-cancels timers bound to destroyed EventTarget contexts and honors cancel_timer # pass 5/5 check.sh: 36: printf: % C: invalid directiveCLI verification output (./files/lab_cli):
learner@ksa:~/gl-q01/lab-m03$ bat listing.txt File: listing.txt coarse_50ms_us=2500 ticks=1 paints=1 work=2Defective starter/ run (exit code 1): emits FAIL: diagnostics on the broken contract assertions.
step 8/15 · 8. explanation of observed behavior
With LIFO traversal, phase-locked do-while deadline advancement, and weak_ptr context validation restored in files/core.cpp, sh check.sh compiles libcore.a cleanly under -std=c++20 -Wall -Wextra -Werror -pedantic and passes all 5/5 TAP version 13 assertions.
step 9/15 · 9. experiment variations
- Near transfer: Add a
remove_filter(EventTarget *watcher)method toEventTarget(matchingQObject::removeEventFilter) and verify removing an active filter mid-session restores directon_eventdelivery. - Far transfer: Add a
next_sleep_ns(std::uint64_t now_ns)query toReactorLoopreturning0whenm_queueis non-empty or the deltaearliest_deadline - now_nssuitable for passing directly into Linuxepoll_pwait2().
step 10/15 · 10. performance measurements
Recorded host benchmark (./files/lab_cli --bench, CLOCK_MONOTONIC, warmup=5, N=40 batches):
learner@ksa:~/gl-q01/lab-m03$ bat listing.txt File: listing.txt BENCH lab_m03_event_loop_timers clock=CLOCK_MONOTONIC benchmark_samples=40 warmup=5 p50_ns=72 p95_ns=73 p99_ns=73 sink=27000The CLOCK_MONOTONIC --bench percentiles measure one timer expiration, two coalesced UpdateRequest posts, and one send_event dispatch per step in host memory (p50 hundreds of nanoseconds). Never confuse host loop overhead with target ARMv7-A epoll_wait wakeup jitter or display controller VSync scanout periods.
step 11/15 · 11. troubleshooting
| Symptom | Root cause | Fix | ||
|---|---|---|---|---|
not ok 3 - drains priority events... | ReactorLoop::send_event walked flts forward (FIFO) instead of reverse (LIFO). | Use for (auto it = flts.rbegin(); it != flts.rend(); ++it) so the last-installed filter runs first. | ||
not ok 4 - computes 5% CoarseTimer window... | Periodic rescheduling set now_ns + due->period_ns and drifted off the 125, 150, 175, 225 grid. | Advance do { due->deadline_ns += due->period_ns; } while (due->deadline_ns <= now_ns);. | ||
not ok 5 - auto-cancels timers bound to destroyed... | ReactorLoop::step() fired a single_shot timer whose EventTarget context had already been destroyed. | Check if (due->has_ctx) and verify `auto sp = due->ctx.lock(); if (!sp | !*sp) before calling due->cb`. |
step 12/15 · 12. guided questions
- Why does
ReactorLoop::step()fire due timers BEFORE drainingm_queue(UpdateRequestat priority-1)?
- *Hint 1:* Think about what a
20 mstelemetry timer callback typically calls on gauges (update()). - *Hint 2:* Firing timers first lets all due timer callbacks update model state and post
UpdateRequest(-1), which then coalesces with any earlierUpdateRequestinto ONE single paint pass in the same turn!
- Why must periodic timer skip-ahead use
while (due->deadline_ns <= now_ns)rather than a singledue->deadline_ns += due->period_ns?
- *Hint 1:* What would happen after a
75 msstall on a25 mstimer (now_ns = 210,deadline_ns = 175) if you only added25once (200 <= 210)? - *Hint 2:* Adding
period_nsonly once leavesdeadline_ns = 200 <= 210, causing the loop to fire a burst of stale catch-up ticks back-to-back instead of resuming cleanly on the next future grid point (225)!
step 13/15 · 13. independent challenges
Extend ReactorLoop::step() with a FrameStats return struct recording max_callback_ns and coalesced_updates using clock_gettime(CLOCK_MONOTONIC) around each due->cb(sched) call so unit tests can fail automatically if any callback exceeds a configurable budget.
step 14/15 · 14. solutions and explanations
The reference files/core.cpp walks dst->filters() in reverse (rbegin()..rend()), advances periodic timers phase-locked via do { due->deadline_ns += due->period_ns; } while (due->deadline_ns <= now_ns);, and checks due->ctx.lock() prior to callback execution.
step 15/15 · run verification and inspect output
Run the verification command and confirm the output matches the expected contract.
learner@ksa:~/gl-q01/lab-m03./files/lab_clilearner@ksa:~/gl-q01/lab-m03coarse_50ms_us=2500 ticks=1 paints=1 work=2Progressive hints & solution
hint 1
Compare starter/Makefile against the module lessons. Focus first on: Builds libcore.a and lab_cli cleanly with -std=c++20 -Wall -Wextra -Werror -pedantic.
hint 2
Compile with -std=c11 -Wall -Wextra -Werror, check every system-call return value before touching output buffers, and verify cleanup on error paths.
solution
warning: Reveal the reference solution files? Running ./check.sh against your own attempt first builds stronger retention.
solution: files/Makefile
learner@ksa:~/gl-q01/lab-m03$ bat files/Makefile File: files/Makefile CC_BIN = g++ AR = ar CFLAGS_ALL = -std=c++20 -Wall -Wextra -Werror -pedantic -O2 LDLIBS = all: libcore.a lab_cli libcore.a: core.o $(AR) rcs $@ $^ lab_cli: cli.o libcore.a $(CC_BIN) $(CFLAGS_ALL) cli.o libcore.a $(LDLIBS) -o $@ %.o: %.cpp core.hpp $(CC_BIN) $(CFLAGS_ALL) -c $< -o $@ .PHONY: all clean clean: rm -f core.o cli.o libcore.a lab_clisolution: files/cli.cpp
learner@ksa:~/gl-q01/lab-m03$ bat files/cli.cpp File: files/cli.cpp #include "core.hpp" #include <algorithm> #include <array> #include <cstdint> #include <cstdio> #include <cstring> #include <ctime> #include <memory> static std::uint64_t now_ns() noexcept { timespec ts{}; clock_gettime(CLOCK_MONOTONIC, &ts); return static_cast<std::uint64_t>(ts.tv_sec) * 1000000000ULL + static_cast<std::uint64_t>(ts.tv_nsec); } static int run_bench() { constexpr int kWarmup = 5; constexpr int kSamples = 40; constexpr int kInner = 200; std::array<std::uint64_t, kSamples> ns{}; volatile std::size_t sink = 0; for (int w = 0; w < kWarmup + kSamples; ++w) { hmi::ReactorLoop loop; hmi::EventTarget panel; std::uint64_t virt_clock = 0; loop.start_timer(0, 10, false, &panel, [&] (std::uint64_t) { loop.post_event(&panel, std::make_unique<hmi::LoopEvent>( hmi::LoopEvent{hmi::EventKind::UpdateRequest, 0}), -1); }); const std::uint64_t t0 = now_ns(); for (int i = 0; i < kInner; ++i) { virt_clock += 10; loop.post_event(&panel, std::make_unique<hmi::LoopEvent>( hmi::LoopEvent{hmi::EventKind::UpdateRequest, 0}), -1); sink += loop.step(virt_clock); } const std::uint64_t dt = (now_ns() - t0) / static_cast<std::uint64_t>(kInner); if (w >= kWarmup) { ns[static_cast<std::size_t>(w - kWarmup)] = dt; } sink += static_cast<std::size_t>(panel.paint_passes); } std::sort(ns.begin(), ns.end()); std::printf("BENCH lab_m03_event_loop_timers clock=CLOCK_MONOTONIC " "benchmark_samples=40 warmup=5 p50_ns=%llu p95_ns=%llu p99_ns=%llu sink=%zu\n", static_cast<unsigned long long>(ns[20]), static_cast<unsigned long long>(ns[38]), static_cast<unsigned long long>(ns[39]), static_cast<std::size_t>(sink)); return 0; } int main(int argc, char **argv) { if (argc > 1 && std::strcmp(argv[1], "--bench") == 0) { return run_bench(); } hmi::ReactorLoop loop; hmi::EventTarget w; int ticks = 0; loop.start_timer(0, 20, false, &w, [&] (std::uint64_t) { ++ticks; }); loop.post_event(&w, std::make_unique<hmi::LoopEvent>(hmi::LoopEvent{hmi::EventKind::UpdateRequest, 0}), -1); loop.post_event(&w, std::make_unique<hmi::LoopEvent>(hmi::LoopEvent{hmi::EventKind::UpdateRequest, 0}), -1); const std::size_t work = loop.step(21); std::printf("coarse_50ms_us=%llu ticks=%d paints=%d work=%zu\n", static_cast<unsigned long long>( hmi::coarse_tolerance_ns(50000000ULL, hmi::TimerKind::Coarse) / 1000ULL), ticks, w.paint_passes, work); return (ticks == 1 && w.paint_passes == 1 && work == 2) ? 0 : 1; }solution: files/core.cpp
learner@ksa:~/gl-q01/lab-m03$ bat files/core.cpp File: files/core.cpp #include "core.hpp" #include <algorithm> namespace hmi { std::uint64_t coarse_tolerance_ns(std::uint64_t period_ns, TimerKind kind) noexcept { return (kind == TimerKind::Coarse) ? (period_ns / 20ULL) : 0ULL; } void EventTarget::install_filter(EventTarget *watcher) { if (!watcher || watcher == this) { return; } m_filters.erase(std::remove(m_filters.begin(), m_filters.end(), watcher), m_filters.end()); m_filters.push_back(watcher); } bool EventTarget::event_filter(EventTarget *, LoopEvent *) { return false; } bool EventTarget::on_event(LoopEvent *ev) { if (ev->kind == EventKind::KeyPress) { ++handled_keys; trace.push_back(ev->code); return true; } if (ev->kind == EventKind::UpdateRequest) { ++paint_passes; return true; } trace.push_back(ev->code); return true; } bool ReactorLoop::send_event(EventTarget *dst, LoopEvent *ev) { if (!dst || !ev) { return false; } const auto &flts = dst->filters(); for (auto it = flts.rbegin(); it != flts.rend(); ++it) { if ((*it)->event_filter(dst, ev)) { return true; } } return dst->on_event(ev); } void ReactorLoop::post_event(EventTarget *dst, std::unique_ptr<LoopEvent> ev, int priority) { if (!dst || !ev) { return; } if (ev->kind == EventKind::UpdateRequest) { for (const auto &q : m_queue) { if (q.dst == dst && q.ev->kind == EventKind::UpdateRequest) { return; } } } m_queue.push_back({priority, m_seq++, dst, std::move(ev)}); } int ReactorLoop::start_timer(std::uint64_t now_ns, std::uint64_t period_ns, bool single_shot, const EventTarget *context, std::function<void(std::uint64_t)> cb) { const int id = m_next_timer++; m_timers.push_back({id, now_ns + period_ns, period_ns, single_shot, true, context != nullptr, context ? context->life_token() : std::weak_ptr<bool>{}, std::move(cb)}); return id; } bool ReactorLoop::cancel_timer(int timer_id) noexcept { for (auto &t : m_timers) { if (t.id == timer_id && t.active) { t.active = false; return true; } } return false; } std::size_t ReactorLoop::step(std::uint64_t now_ns) { std::size_t work = 0; for (;;) { TimerEntry *due = nullptr; for (auto &t : m_timers) { if (!t.active || t.deadline_ns > now_ns) { continue; } if (!due || t.deadline_ns < due->deadline_ns || (t.deadline_ns == due->deadline_ns && t.id < due->id)) { due = &t; } } if (!due) { break; } if (due->has_ctx) { auto sp = due->ctx.lock(); if (!sp || !*sp) { due->active = false; continue; } } const std::uint64_t sched = due->deadline_ns; if (due->single_shot || due->period_ns == 0) { due->active = false; } else { do { due->deadline_ns += due->period_ns; } while (due->deadline_ns <= now_ns); } due->cb(sched); ++work; } std::sort(m_queue.begin(), m_queue.end(), [] (const Queued &a, const Queued &b) { if (a.priority != b.priority) { return a.priority > b.priority; } return a.seq < b.seq; }); while (!m_queue.empty()) { Queued item = std::move(m_queue.front()); m_queue.erase(m_queue.begin()); send_event(item.dst, item.ev.get()); ++work; } return work; } } // namespace hmisolution: files/core.hpp
learner@ksa:~/gl-q01/lab-m03$ bat files/core.hpp File: files/core.hpp #pragma once #include <cstddef> #include <cstdint> #include <functional> #include <memory> #include <vector> namespace hmi { enum class EventKind { KeyPress, UpdateRequest, Custom }; enum class TimerKind { Precise, Coarse }; struct LoopEvent { EventKind kind; int code = 0; }; class EventTarget { public: EventTarget() : m_alive(std::make_shared<bool>(true)) {} virtual ~EventTarget() { *m_alive = false; } EventTarget(const EventTarget &) = delete; EventTarget &operator=(const EventTarget &) = delete; std::weak_ptr<bool> life_token() const noexcept { return m_alive; } void install_filter(EventTarget *watcher); virtual bool event_filter(EventTarget *watched, LoopEvent *ev); virtual bool on_event(LoopEvent *ev); const std::vector<EventTarget *> &filters() const noexcept { return m_filters; } int handled_keys = 0; int paint_passes = 0; std::vector<int> trace; private: std::shared_ptr<bool> m_alive; std::vector<EventTarget *> m_filters; }; std::uint64_t coarse_tolerance_ns(std::uint64_t period_ns, TimerKind kind) noexcept; class ReactorLoop { public: static bool send_event(EventTarget *dst, LoopEvent *ev); void post_event(EventTarget *dst, std::unique_ptr<LoopEvent> ev, int priority = 0); int start_timer(std::uint64_t now_ns, std::uint64_t period_ns, bool single_shot, const EventTarget *context, std::function<void(std::uint64_t)> cb); bool cancel_timer(int timer_id) noexcept; std::size_t step(std::uint64_t now_ns); private: struct Queued { int priority; std::size_t seq; EventTarget *dst; std::unique_ptr<LoopEvent> ev; }; struct TimerEntry { int id; std::uint64_t deadline_ns; std::uint64_t period_ns; bool single_shot; bool active; bool has_ctx; std::weak_ptr<bool> ctx; std::function<void(std::uint64_t)> cb; }; std::size_t m_seq = 0; int m_next_timer = 1; std::vector<Queued> m_queue; std::vector<TimerEntry> m_timers; }; } // namespace hmiRun the check
From labs/lab_m03_event_loop_timers/, run ./check.sh. A complete solution emits TAP version 13 with every test point marked ok and exits 0:
learner@ksa:~/gl-q01/lab-m03./check.shTAP version 131..5ok 1 - builds libcore.a and lab_cli cleanly with -std=c++20 -Wall -Wextra -Werror -pedanticok 2 - archives core.o into libcore.a and links independent TAP verifierok 3 - drains priority events, coalesces UpdateRequest, and runs event_filter in LIFO orderok 4 - computes 5ok 5 - auto-cancels timers bound to destroyed EventTarget contexts and honors cancel_timer# pass 5/5check.sh: 36: printf: % C: invalid directiveOn an incomplete starter tree, ./check.sh exits non-zero and marks the unmet assertion not ok with an indented YAML diagnostic block:
learner@ksa:~/gl-q01/lab-m03./check.shTAP version 131..5ok 1 - builds libcore.a and lab_cli cleanly with -std=c++20 -Wall -Wextra -Werror -pedanticok 2 - archives core.o into libcore.a and links independent TAP verifiernot ok 3 - drains priority events, coalesces UpdateRequest, and runs event_filter in LIFO orderFAIL: traverse dst->filters() with rbegin()..rend() in ReactorLoop::send_event and compress UpdateRequest in post_event --- message: 'got LIFO filter failed to short-circuit blocked key' hint: 'traverse dst->filters() with rbegin()..rend() in ReactorLoop::send_event and compress UpdateRequest in post_event' ...not ok 4 - computes 5FAIL: advance due->deadline_ns += due->period_ns in a do-while (due->deadline_ns <= now_ns) loop instead of now_ns + period_ns --- message: 'got phase-locked schedule drifted, fires.size=3' hint: 'advance due->deadline_ns += due->period_ns in a do-while (due->deadline_ns <= now_ns) loop instead of now_ns + period_ns' ...not ok 5 - auto-cancels timers bound to destroyed EventTarget contexts and honors cancel_timerFAIL: lock due->ctx when due->has_ctx is true in ReactorLoop::step and deactivate expired timers before invoking cb --- message: 'got destroyed context singleShot fired 1 times!' hint: 'lock due->ctx when due->has_ctx is true in ReactorLoop::step and deactivate expired timers before invoking cb' ...# pass 2/5check.sh: 39: printf: % C: invalid directivenote: How to read TAP diagnostics: 1..N states the total test plan; each ok k confirms a passed check; not ok k pinpoints the failing check alongside message: (what went wrong) and hint: (where to look next) between --- and ....
inspect harness: check.sh
learner@ksa:~/gl-q01/lab-m03$ bat check.sh File: check.sh #!/bin/sh set -u cd "$(dirname "$0")" || exit 1 PASS=0 WORK=$(mktemp -d "${TMPDIR:-/tmp}/ksa_lab.XXXXXX") || exit 1 trap 'rm -rf "$WORK"' EXIT HUP INT TERM cp -R files "$WORK/files" printf 'TAP version 13\n1..5\n' if make -B -C "$WORK/files" >"$WORK/build.log" 2>&1; then printf 'ok 1 - builds libcore.a and lab_cli cleanly with -std=c++20 -Wall -Wextra -Werror -pedantic\n' PASS=$((PASS + 1)) else printf 'not ok 1 - builds libcore.a and lab_cli cleanly with -std=c++20 -Wall -Wextra -Werror -pedantic\n' printf 'FAIL: fix compiler warnings or errors in files/core.cpp\n' fi if [ -f "$WORK/files/libcore.a" ] && g++ -std=c++20 -Wall -Wextra -Werror -pedantic -O2 -I"$WORK/files" tests.cpp "$WORK/files/libcore.a" -o "$WORK/verify" >>"$WORK/build.log" 2>&1; then printf 'ok 2 - archives core.o into libcore.a and links independent TAP verifier\n' PASS=$((PASS + 1)) else printf 'not ok 2 - archives core.o into libcore.a and links independent TAP verifier\n' printf 'FAIL: preserve public declarations in files/core.hpp so tests.cpp links\n' fi if [ -x "$WORK/verify" ] && OUT=$("$WORK/verify" 1 2>&1); then printf 'ok 3 - drains priority events, coalesces UpdateRequest, and runs event_filter in LIFO order\n' PASS=$((PASS + 1)) else printf 'not ok 3 - drains priority events, coalesces UpdateRequest, and runs event_filter in LIFO order\n' printf 'FAIL: traverse dst->filters() with rbegin()..rend() in ReactorLoop::send_event and compress UpdateRequest in post_event\n' printf " ---\n message: 'got %s'\n hint: 'traverse dst->filters() with rbegin()..rend() in ReactorLoop::send_event and compress UpdateRequest in post_event'\n ...\n" "${OUT:-build_failed}" fi if [ -x "$WORK/verify" ] && OUT=$("$WORK/verify" 2 2>&1); then printf 'ok 4 - computes 5% CoarseTimer window and advances periodic deadlines phase-locked across stalls\n' PASS=$((PASS + 1)) else printf 'not ok 4 - computes 5% CoarseTimer window and advances periodic deadlines phase-locked across stalls\n' printf 'FAIL: advance due->deadline_ns += due->period_ns in a do-while (due->deadline_ns <= now_ns) loop instead of now_ns + period_ns\n' printf " ---\n message: 'got %s'\n hint: 'advance due->deadline_ns += due->period_ns in a do-while (due->deadline_ns <= now_ns) loop instead of now_ns + period_ns'\n ...\n" "${OUT:-build_failed}" fi if [ -x "$WORK/verify" ] && OUT=$("$WORK/verify" 3 2>&1); then printf 'ok 5 - auto-cancels timers bound to destroyed EventTarget contexts and honors cancel_timer\n' PASS=$((PASS + 1)) else printf 'not ok 5 - auto-cancels timers bound to destroyed EventTarget contexts and honors cancel_timer\n' printf 'FAIL: lock due->ctx when due->has_ctx is true in ReactorLoop::step and deactivate expired timers before invoking cb\n' printf " ---\n message: 'got %s'\n hint: 'lock due->ctx when due->has_ctx is true in ReactorLoop::step and deactivate expired timers before invoking cb'\n ...\n" "${OUT:-build_failed}" fi printf '# pass %d/5\n' "$PASS" [ "$PASS" -eq 5 ]Definition of done
Verification checklist
status: 0/3 checks verified
Troubleshooting
Compiler fails under -Werror on sign conversion or unused args
Use exact POSIX return types (ssize_t for read()/write(), size_t for byte counts) rather than relaxing flags.
./check.sh reports missing files in files/
Invoke ./check.sh from inside labs/lab_m03_event_loop_timers/ so relative paths to files/ resolve directly.