Drift-free periodic wake-up
Compute how long a periodic task should sleep so its period never drifts. A medium embedded C problem (RTOS scheduling), run and graded in the browser.
medium · RTOS scheduling · rtos · ticks · rollover
A task that runs its work and then sleeps for period ticks drifts: its period is really period plus however long the work took. RTOSes provide "delay until" instead, which wakes at fixed multiples of the period from a stored reference.
*last_wake is the tick at which the task last woke. Advance it by one period, and return how many ticks to sleep from now until then. If that time has already passed (the task overran), return 0; the next call will catch up.
The tick counter is 32 bits and may wrap. Less than one wrap ever separates *last_wake and now.
Starter code
uint32_t next_wake(uint32_t *last_wake, uint32_t period, uint32_t now) {
*last_wake = now + period;
return period;
}Example tests
Sleep for the rest of the period
uint32_t last = 1000;
uint32_t a = next_wake(&last, 100, 1030);
uint32_t b = next_wake(&last, 100, 1105);
printf("%u %u %u\n", a, b, last);Expected output:
70 95 1200Catching up after an overrun
uint32_t last = 1000;
uint32_t a = next_wake(&last, 100, 1250);
uint32_t b = next_wake(&last, 100, 1250);
uint32_t c = next_wake(&last, 100, 1250);
printf("%u %u %u %u\n", a, b, c, last);Expected output:
0 0 50 1300Learn it first
- RTOS scheduling and timing · Preemption, context switches, ticks and rate-monotonic analysis.
More RTOS scheduling problems
- Response-time analysis · Compute worst-case response times under fixed-priority scheduling and check every deadline.
- Find the highest ready priority · Pick the highest priority from a 32-bit ready bitmap.
- Rate-monotonic utilisation test · Decide from CPU utilisation whether a task set is schedulable under rate-monotonic priorities.
- Priorities with round-robin · Choose the next task to run, sharing the CPU in turns among tasks of equal priority.
- Earliest-deadline-first schedule · Simulate an EDF scheduler tick by tick, draw the timeline and count missed deadlines.
- Priority inversion, tick by tick · Simulate a preemptive scheduler with a shared mutex, and see what priority inheritance changes.
- Ventilator: will every task meet its deadline? · Prove the ventilator's tasks are schedulable with response-time analysis, not just a utilisation total.