Monotonic QTimer, Precise vs Coarse Coalescing & GUI Frame Stalls
Drive periodic QTimer cadences from CLOCK_MONOTONIC, choose Qt::PreciseTimer versus Qt::CoarseTimer's 5% coalescing window deliberately, and prevent blocking slots from starving QPaintEvent.
What you'll learn
- Prove why
CLOCK_MONOTONICphase-locked advancement (deadline += period) eliminates cumulative drift and survives NTP wall-clock jumps. - Select
Qt::PreciseTimerversusQt::CoarseTimer(5%coalescing window) and bindQTimer::singleShotsafely to receiver lifetimes. - Instrument GUI slot execution budgets with
QElapsedTimerto catch main-thread stalls that starveQPaintEvent/WM_PAINTdelivery.
Wall-Clock Jumps, 5% Timer Jitter & Cooperative Frame Starvation
Embedded Linux panels frequently boot with 1970-01-01 RTC time before chronyd steps CLOCK_REALTIME forward by decades—or an operator adjusts shift time backward by five minutes. Any timeout computed from QDateTime::currentMSecsSinceEpoch() either fires early or freezes for five minutes! Both QTimer and QElapsedTimer anchor exclusively to the Linux kernel's CLOCK_MONOTONIC, which ticks strictly upward from boot.
Even on CLOCK_MONOTONIC, three behaviors catch engineers off guard. First, QTimer defaults to Qt::CoarseTimer, shifting deadlines by up to 5% (+/-2.5 ms on a 50 ms timer) to group CPU wakeups; tight 20 ms HMI scopes need Qt::PreciseTimer. Second, QTimer is NOT a preemptive POSIX signal or hardware interrupt! It is an entry in the thread's QTimerInfoList min-heap: if a synchronous slot blocks the GUI thread for 100 ms, neither QTimer nor QPaintEvent (WM_PAINT / UpdateRequest) can run until that slot returns!
Figure 3.3a. GUI-thread QTimers and QPaintEvents share one cooperative thread: blocking any slot freezes both timers and screen repaints.
mental model: Phase-locked CLOCK_MONOTONIC scheduling (next += 20 ms) is like a metro line dispatching trains at :00, :20, and :40 off an atomic station clock rather than starting a 20-minute kitchen timer after each train finishes boarding—and if a blocked track holds the platform until :52, the dispatcher skips missed :20/:40 slots and schedules :60 cleanly instead of launching three trains bumper-to-bumper.
Where it stops working: Even Qt::PreciseTimer in standard user space is bounded by Linux kernel scheduler wakeup jitter (typically 50-500 us on normal kernels); sub-50 us deterministic control loops belong on a PREEMPT_RT SCHED_FIFO worker thread or dedicated microcontroller, never on the GUI rendering thread.
definition (QTimerInfoList, Qt::TimerType, and QElapsedTimer): QTimerInfoList is Qt's per-thread monotonic deadline queue feeding the timeout parameter of ppoll() / epoll_wait(). Qt::TimerType selects wakeup rounding: Qt::PreciseTimer preserves exact millisecond/nanosecond deadlines, Qt::CoarseTimer (default) adjusts intervals by up to 5% to align neighboring timers, and Qt::VeryCoarseTimer snaps to whole seconds. QElapsedTimer is an allocation-free 8-byte wrapper over clock_gettime(CLOCK_MONOTONIC).
- Step 1. Call setTimerType() before start() whenever +/-5% coarse jitter is unacceptable.
- Step 2. Pass 'this' as the 2nd argument to QTimer::singleShot so widget destruction cancels delayed slots.
- Step 3. Anchor periodic deadlines to the initial monotonic phase and skip past missed intervals after stalls.
- Step 4. Measure slot duration and inter-tick delta with QElapsedTimer to surface hidden main-thread stalls.
Figure 3.3b. Use CLOCK_MONOTONIC phase grids, PreciseTimer for cadence, and <8 ms GUI slots so Paint runs.
How Blocking Slots Starve Both QTimerInfoList and QPaintEvent
Trace one turn of QApplication::exec() on a 60 Hz (16.67 ms period) industrial touchscreen: (1) epoll_wait wakes at t = 20.0 ms because a Qt::PreciseTimer expired; (2) QTimerInfoList::activateTimers() emits timeout(), invoking your slot; (3) your slot calls gauge->update(), queueing a LowEventPriority UpdateRequest; and (4) ONLY AFTER your slot returns does Qt drain UpdateRequest to issue QPaintEvent (or WM_PAINT on Windows / surface commit on Wayland)!
If step (2) performs a synchronous 90 ms serial retry or unindexed SQLite scan, step (4) cannot execute for 90 ms—dropping five consecutive 60 Hz frames—and the 20 ms timer misses ticks at 40, 60, and 80 ms! In monotonic_frame_watchdog.cpp below, FrameWatchdog monitors BOTH slotUs (catching our own slow slot) AND interTickUs (catching any OTHER slow slot on the GUI thread that delayed our wakeup), while binding QTimer::singleShot safely to this.
Figure 3.3b. Keeping GUI-thread slots under 4-8 ms leaves ample headroom inside each 16.67 ms VSync interval for layout and QPainter rasterization.
| Timing Primitive / API | Underlying Clock / Mode | Behavior Across NTP / Stalls | Recommended HMI Role |
|---|---|---|---|
QDateTime::currentMSecsSinceEpoch | CLOCK_REALTIME (wall clock) | Jumps backward/forward on NTP sync! | Human audit timestamps ONLY; never timeouts |
QElapsedTimer::nsecsElapsed() | CLOCK_MONOTONIC (8 B value) | Strictly non-decreasing; zero heap cost | Slot latency budgets, retry deadlines, FPS math |
QTimer (Qt::CoarseTimer, default) | CLOCK_MONOTONIC + 5% batching | Shifts up to 5%; skips missed stall ticks | Status blinks, tooltips, non-critical UI polls |
QTimer (Qt::PreciseTimer) | CLOCK_MONOTONIC exact deadline | Phase-locked; still blocked by slow GUI slots | 20-60 Hz waveform strip charts & watchdogs |
learner@ksa:~/gl-q01/m03-l03$ bat -H 16 -H 25 monotonic_frame_watchdog.cpp File: monotonic_frame_watchdog.cpp #include <QElapsedTimer> #include <QObject> #include <QTimer> #include <cstdint> namespace hmi { class FrameWatchdog final : public QObject { Q_OBJECT public: static constexpr int kPeriodMs = 20; static constexpr std::int64_t kSlotBudgetUs = 8000; // 8 ms (< 16.67 ms 60 Hz) explicit FrameWatchdog(QObject *parent = nullptr) : QObject(parent), m_timer(new QTimer(this)) { m_timer->setTimerType(Qt::PreciseTimer); m_timer->setInterval(kPeriodMs); connect(m_timer, &QTimer::timeout, this, &FrameWatchdog::onTick); } void startWithWarmupBanner() { m_interTick.start(); m_timer->start(); // Context-bound singleShot: auto-cancels if FrameWatchdog dies < 250 ms! QTimer::singleShot(250, this, &FrameWatchdog::warmupFinished); } signals: void pollTelemetry(); void warmupFinished(); void frameStallDetected(std::int64_t slotUs, std::int64_t interTickUs); private slots: void onTick() { const std::int64_t interUs = m_interTick.nsecsElapsed() / 1000; m_interTick.restart(); QElapsedTimer slotClock; slotClock.start(); emit pollTelemetry(); const std::int64_t slotUs = slotClock.nsecsElapsed() / 1000; if (slotUs > kSlotBudgetUs || interUs > (kPeriodMs * 1500LL)) { emit frameStallDetected(slotUs, interUs); } } private: QTimer *m_timer = nullptr; QElapsedTimer m_interTick; }; } // namespace hmi- Qt::PreciseTimer disables default 5% CoarseTimer rounding on the 20 ms telemetry cadence.
- Passing 'this' as the 2nd argument to QTimer::singleShot cancels the 250 ms callback if FrameWatchdog is deleted early.
QTimer-QElapsedTimer(3qt) GL-Q01 Quick Reference QTimer-QElapsedTimer(3qt) NAME QTimer, QElapsedTimer, Qt::TimerType - monotonic scheduling & stall measurement SYNOPSIS void QTimer::setTimerType(Qt::TimerType atype); // PreciseTimer | CoarseTimer static void QTimer::singleShot(int msec, const QObject *context, Functor slot); qint64 QElapsedTimer::nsecsElapsed() const noexcept; MONOTONICITY & COOPERATIVE LOOP RULES 1. Both QTimer and QElapsedTimer use CLOCK_MONOTONIC (immune to NTP jumps). 2. Default Qt::CoarseTimer coalesces deadlines within a 5% interval window. 3. A GUI-thread QTimer cannot preempt a busy slot; blocking the main thread starves both QTimer callbacks and QPaintEvent (WM_PAINT) frame rendering. Kernel Systems Academy Lesson 3.3 QTimer-QElapsedTimer(3qt) GL-Q01 quick reference · full manual page: man 3qt QTimer-QElapsedTimer Proving Monotonic Phase-Lock, 5% Coarse Window & Paint Starvation in C++20
In verify.cpp, we invoke the Linux kernel SYS_clock_gettime syscall with CLOCK_MONOTONIC directly so strace captures the kernel monotonic clock read explicitly, then run a deterministic TimerLoop proving four invariants: (1) coarse_window_ns() computes Qt's 5% coalescing bound versus 0 for PreciseTimer; (2) late OS wakeups (21 ms, 42 ms, 61 ms) stay locked to the 20/40/60 ms phase grid; (3) a 75 ms blocking slot (61 -> 136 ms) starves queued paint requests during the stall and skips stale 80/100/120 ms ticks cleanly to 140 ms; and (4) destroying a context token cancels a pending single_shot timer before it fires!
learner@ksa:~/gl-q01/m03-l03$ bat -H 16 -H 63 verify.cpp File: verify.cpp #include <cassert> #include <cstdint> #include <cstdio> #include <ctime> #include <functional> #include <memory> #include <sys/syscall.h> #include <unistd.h> #include <vector> namespace hmi { enum class TimerMode { Precise, Coarse }; static std::uint64_t kernel_monotonic_ns() { timespec ts{}; const long rc = ::syscall(SYS_clock_gettime, CLOCK_MONOTONIC, &ts); assert(rc == 0); return static_cast<std::uint64_t>(ts.tv_sec) * 1000000000ULL + static_cast<std::uint64_t>(ts.tv_nsec); } static constexpr std::uint64_t coarse_window_ns(std::uint64_t period_ns, TimerMode mode) noexcept { return (mode == TimerMode::Coarse) ? (period_ns / 20ULL) : 0ULL; // 5% window } class TimerWheel { public: int add(std::uint64_t start_ns, std::uint64_t period_ns, bool single_shot, std::weak_ptr<bool> ctx, std::function<void(std::uint64_t)> cb) { const int id = m_next_id++; m_items.push_back({id, start_ns + period_ns, period_ns, single_shot, true, std::move(ctx), std::move(cb)}); return id; } int advance(std::uint64_t now_ns, bool &paint_pending, int &paints_rendered) { int fired = 0; for (;;) { Item *due = nullptr; for (auto &it : m_items) { if (!it.active || it.deadline_ns > now_ns) { continue; } if (!due || it.deadline_ns < due->deadline_ns || (it.deadline_ns == due->deadline_ns && it.id < due->id)) { due = ⁢ } } if (!due) { break; } auto alive = due->ctx.lock(); if (!alive || !*alive) { due->active = false; continue; } const std::uint64_t sched = due->deadline_ns; if (due->single_shot) { due->active = false; } else { do { due->deadline_ns += due->period_ns; } while (due->deadline_ns <= now_ns); } due->cb(sched); ++fired; } // Cooperative LowEventPriority paint runs ONLY after all due timer slots finish! if (paint_pending) { paint_pending = false; ++paints_rendered; } return fired; } std::uint64_t next_deadline(int id) const noexcept { for (const auto &it : m_items) { if (it.id == id && it.active) { return it.deadline_ns; } } return 0; } private: struct Item { int id; std::uint64_t deadline_ns; std::uint64_t period_ns; bool single_shot; bool active; std::weak_ptr<bool> ctx; std::function<void(std::uint64_t)> cb; }; int m_next_id = 1; std::vector<Item> m_items; }; } // namespace hmi int main() { constexpr std::uint64_t kMs = 1000000ULL; static_assert(hmi::coarse_window_ns(50 * kMs, hmi::TimerMode::Coarse) == 2500000ULL); static_assert(hmi::coarse_window_ns(50 * kMs, hmi::TimerMode::Precise) == 0ULL); const std::uint64_t t0 = hmi::kernel_monotonic_ns(); const std::uint64_t t1 = hmi::kernel_monotonic_ns(); assert(t1 >= t0); hmi::TimerWheel wheel; auto app_ctx = std::make_shared<bool>(true); auto popup_ctx = std::make_shared<bool>(true); bool paint_dirty = false; int paint_frames = 0; int cancelled_oneshot = 0; std::vector<std::uint64_t> grid_ms; const int pid = wheel.add(t0, 20 * kMs, false, app_ctx, [&] (std::uint64_t sched) { grid_ms.push_back((sched - t0) / kMs); paint_dirty = true; }); wheel.add(t0, 50 * kMs, true, popup_ctx, [&] (std::uint64_t) { ++cancelled_oneshot; }); wheel.advance(t0 + 21 * kMs, paint_dirty, paint_frames); *popup_ctx = false; // Destroy popup at 30 ms before 50 ms singleShot expires! wheel.advance(t0 + 42 * kMs, paint_dirty, paint_frames); wheel.advance(t0 + 61 * kMs, paint_dirty, paint_frames); assert((grid_ms == std::vector<std::uint64_t>{20, 40, 60})); assert(cancelled_oneshot == 0 && paint_frames == 3); // 75 ms GUI stall (61ms -> 136ms): misses 80/100/120 into 1 fire, next = 140ms! const int post_stall_fires = wheel.advance(t0 + 136 * kMs, paint_dirty, paint_frames); assert(post_stall_fires == 1 && paint_frames == 4); assert((wheel.next_deadline(pid) - t0) / kMs == 140); std::printf("Timer mono_dt=%lluns coarse50=%lluus grid=%zu oneshot_cancelled=%d next=%llums\n", static_cast<unsigned long long>(t1 - t0), static_cast<unsigned long long>( hmi::coarse_window_ns(50 * kMs, hmi::TimerMode::Coarse) / 1000ULL), grid_ms.size(), (cancelled_oneshot == 0) ? 1 : 0, static_cast<unsigned long long>((wheel.next_deadline(pid) - t0) / kMs)); return 0; }- Direct SYS_clock_gettime(CLOCK_MONOTONIC) syscall proves monotonic kernel clock anchor in strace.
- do { deadline_ns += period_ns; } while (deadline_ns <= now_ns) locks phase and skips stale stall multiples.
Inspecting CLOCK_MONOTONIC Syscalls and Post-Stall Phase Alignment
Inspect both ./verify stdout and the strace capture! ./verify prints coarse50=2500us grid=4 oneshot_cancelled=1 next=140ms: 5% of 50 ms equals 2500 us, destroying popup_ctx at 30 ms cancelled the 50 ms singleShot (oneshot_cancelled=1), and recovering at 136 ms from a 75 ms stall coalesced missed intervals into one callback and locked the next deadline to 140 ms.
In strace, confirm the two real clock_gettime(CLOCK_MONOTONIC, ...) kernel calls preceding write(1, ...) and exit_group(0).
learner@ksa:~/gl-q01/m03-l03g++ -std=c++20 -Wall -Wextra -Werror -pedantic verify.cpp -o verifylearner@ksa:~/gl-q01/m03-l03./verifyTimer mono_dt=579ns coarse50=2500us grid=4 oneshot_cancelled=1 next=140mslearner@ksa:~/gl-q01/m03-l03learner@ksa:~/gl-q01/m03-l03strace -e trace=clock_gettime,write,exit_group \./verifyclock_gettime(CLOCK_MONOTONIC, {tv_sec=1136271, tv_nsec=834146}) = 0clock_gettime(CLOCK_MONOTONIC, {tv_sec=1136271, tv_nsec=893476}) = 0write(1, "Timer mono_dt=59330ns coarse50=2"..., 76) = 76exit_group(0) = ?+++ exited with 0 +++0-ms Busy Spin Timers, Contextless singleShot & Wall-Clock Timeouts
You have now mastered Qt 6's entire core runtime triad across Modules 1–3: C++20 + QObject ownership trees, d_ptr + uic + moc void ** meta-dispatch, and PMF context lifetimes + LIFO eventFilter chains + CLOCK_MONOTONIC timers.
Complete the lab_m03_event_loop_timers studio below to integrate priority posted events, LIFO filters, and phase-locked monotonic timers into a single verified C++20 reactor library.
Starting an Unthrottled 0-ms Periodic QTimer (start(0)) on Embedded Linux:
- Symptom:
topshows the HMI binary pegged at100%CPU usage on oneCortex-A7core even when nothing on screen is changing, overheating the enclosure. - Root Cause: A
0 msperiodicQTimerfires every single time the event queue finishes draining normal events, preventingppoll()/epoll_wait()from ever sleeping in the kernel! - Fix: Use
QTimer::singleShot(0, this, slot)ONLY for one-time deferred post-construction work; drive recurring polls with explicit frame/sensor periods (20-100 ms) orQSocketNotifierfd readiness.
Calling 2-Argument QTimer::singleShot(500, [this] { ... }) Without Receiver Context:
- Symptom: Closing a transient notification toast within 500 ms of opening it causes a segmentation fault half a second later inside the fade-out lambda.
- Root Cause: Just like 3-argument
QObject::connect, 2-argumentQTimer::singleShot(msec, functor)has NO contextQObject *and fires unconditionally aftermseceven ifthiswas deleted! - Fix: Always call the 3-argument overload
QTimer::singleShot(500, this, [this] { ... })(or&Toast::fadeOut) so~Toast()cancels the timer automatically.
Guided Practice
Add a simulated NTP backward wall-clock jump (realtime_offset_ns -= 30 * 1000000000ULL) to verify.cpp alongside kernel_monotonic_ns(), and demonstrate in a short helper function why a wall-clock deadline hangs for 30 extra seconds while TimerWheel on CLOCK_MONOTONIC fires right on its 20 ms schedule.
Independent Practice
Open labs/lab_m03_event_loop_timers/ and repair all three defects in starter/core.cpp—inverted FIFO filter order, cumulative now_ns + period_ns timer drift, and missing receiver context-token cancellation—until sh check.sh passes 5/5 TAP version 13 checks and ./files/lab_cli --bench outputs CLOCK_MONOTONIC percentiles.
Verification Checks
→ open standalone lab workbench
1. Motivation
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.
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.
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).
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.
5. Complete executable commands
learner@ksa:~/gl-q01/m03-l03$ bat script.sh File: script.sh make -B -C files ./files/lab_cli ./files/lab_cli --bench sh check.sh6. Annotated source code
files/core.cpp enforces the production invariants that starter/core.cpp breaks:
learner@ksa:~/gl-q01/m03-l03$ 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().
7. Expected output
Passing files/ run (sh check.sh, exit code 0):
learner@ksa:~/gl-q01/m03-l03$ 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/m03-l03$ 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.
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.
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().
10. Performance measurements
Recorded host benchmark (./files/lab_cli --bench, CLOCK_MONOTONIC, warmup=5, N=40 batches):
learner@ksa:~/gl-q01/m03-l03$ 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.
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`. |
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)!
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.
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.
Run locally in your terminal and check off each verification milestone.
Not started
Key takeaways
QTimerandQElapsedTimerschedule deadlines onCLOCK_MONOTONIC, advancing periodic targets phase-locked (next_ns += period_ns) so NTP or operator wall-clock jumps never freeze or burst HMI timers.QTimerdefaults toQt::CoarseTimer, which rounds wakeups within a5%interval window to batch OS wakeups; deterministic control/telemetry cadences requiresetTimerType(Qt::PreciseTimer).- Context-bound
QTimer::singleShot(ms, receiver, slot)cancels pending one-shot callbacks automatically ifreceiveris destroyed before the deadline expires. - Because
QTimerandQPaintEvent(WM_PAINT/UpdateRequest) share the cooperative GUI event loop, blocking a GUI-thread slot for90 msdelays every GUIQTimerand freezes frame rendering for90 ms.