RTOS scheduling and timing
Preemption, context switches, ticks and rate-monotonic analysis.
Who runs next
The scheduler decides which ready task gets the CPU. Almost every RTOS uses fixed-priority preemptive scheduling: the highest-priority ready task always runs, and if a higher-priority task becomes ready (because its delay expired or it received a message), it preempts the running one immediately.
Preemptive versus cooperative
| Preemptive | Cooperative | |
|---|---|---|
| Task switch happens | Whenever a higher-priority task becomes ready | Only when the running task yields or blocks |
| Response time of urgent work | Bounded and short | Depends on the longest-running task |
| Shared data | Needs protection (any line can be interrupted) | Simpler: no switch mid-section |
| Typical | FreeRTOS, Zephyr, most RTOSes | Simple schedulers, some protothread libraries |
With tasks of equal priority, most kernels time-slice: they share the CPU in turn at each tick. FreeRTOS does this when configUSE_TIME_SLICING is set.
The tick
The kernel keeps time with a periodic interrupt (SysTick on Cortex-M), typically 1 kHz. On each tick it advances time, wakes tasks whose delays have expired and, if time-slicing, rotates equal-priority tasks.
Consequences:
- Delays are measured in ticks:
vTaskDelay(pdMS_TO_TICKS(10))at 1 kHz waits 9 to 10 ms, because the first tick may arrive almost immediately. - For periodic tasks, use
vTaskDelayUntil(absolute wake times), notvTaskDelayin a loop, which drifts by the task's execution time each period. - A tickless idle mode stops the tick while all tasks are blocked and programs a low-power timer for the next wake-up, which is essential for battery devices.
Context switching
A context switch saves the running task's registers on its stack, stores its stack pointer, picks the next task, restores that task's stack pointer and registers. On Cortex-M:
- The hardware automatically stacks R0 to R3, R12, LR, PC and xPSR on exception entry.
- The kernel's PendSV handler saves R4 to R11 (and FPU registers S16 to S31 if the task used the FPU), switches
PSPto the next task's stack, and restores. - PendSV runs at the lowest interrupt priority, so a context switch never delays a real interrupt, and switches requested from several ISRs collapse into one.
A switch typically takes a few hundred cycles to a microsecond or two.
Choosing priorities: rate-monotonic
For periodic tasks with deadlines equal to their periods, rate-monotonic scheduling (RMS) is the optimal fixed-priority assignment: the shorter the period, the higher the priority. Priorities follow urgency, not importance; the "most important" task can still be low priority if its deadline is long.
The utilisation test
Each task has worst-case execution time C and period T. Its utilisation is C / T. Liu and Layland showed that n tasks are guaranteed schedulable under RMS if:
U = sum(C_i / T_i) <= n * (2^(1/n) - 1)
The bound is 100% for 1 task, 82.8% for 2, 78.0% for 3, and approaches ln 2 ≈ 69.3% for many. It is sufficient, not necessary: a set above the bound may still be schedulable, which response-time analysis decides exactly.
#include <stdio.h>
#include <math.h>
typedef struct { const char *name; double c_ms, t_ms; } task_t;
int main(void) {
task_t ts[] = { { "control", 1.0, 5.0 }, { "sensors", 3.0, 20.0 }, { "comms", 10.0, 50.0 } };
int n = 3;
double u = 0;
for (int i = 0; i < n; i++) u += ts[i].c_ms / ts[i].t_ms;
double bound = n * (pow(2.0, 1.0 / n) - 1);
printf("utilisation %.1f%%, RMS bound %.1f%% -> %s\n", u * 100, bound * 100,
u <= bound ? "guaranteed schedulable" : "needs response-time analysis");
/* Exact check: R = C + sum over higher-priority tasks of ceil(R / Tj) * Cj */
for (int i = 0; i < n; i++) {
double r = ts[i].c_ms, prev = 0;
while (r != prev && r <= ts[i].t_ms) {
prev = r;
r = ts[i].c_ms;
for (int j = 0; j < i; j++) r += ceil(prev / ts[j].t_ms) * ts[j].c_ms;
}
printf("%-8s worst-case response %4.1f ms, deadline %4.1f ms %s\n",
ts[i].name, r, ts[i].t_ms, r <= ts[i].t_ms ? "ok" : "MISSED");
}
return 0;
}
In practice, measure worst-case execution times on the target (cycle counter, trace tools), include interrupt load and kernel overhead, and keep margin.
Earliest deadline first
EDF scheduling dynamically runs whichever ready task has the nearest deadline. It can reach 100% utilisation, but is rarer in commercial RTOSes, behaves worse under overload (many tasks miss at once), and needs deadline information at run time.
Timing problems to recognise
- Starvation: a high-priority task that never blocks stops all lower-priority tasks. Every task must block somewhere.
- Priority inversion: a high-priority task waits for a resource held by a low-priority task, which is preempted by a medium-priority one. Solved by mutexes with priority inheritance (see the synchronisation guide).
- Jitter: variation in when a periodic task actually runs, caused by higher-priority tasks and interrupts. Put the jitter-sensitive part (sampling, output updates) in a timer interrupt or hardware, not a task.
- Tick resolution: sub-tick timing needs a hardware timer, not a task delay.
Pitfall: Setting every task to the same high priority "to make them all fast" turns a priority scheduler into round-robin with unpredictable latency. Assign priorities by deadline and keep the number of levels small.
Interview question: Why is vTaskDelayUntil preferred over vTaskDelay for a periodic task?
Answer: vTaskDelay blocks for a duration relative to when it is called, so the period becomes execution time plus delay, and any variation (preemption, varying work) makes the timing drift. vTaskDelayUntil blocks until an absolute wake time that advances by exactly the period each cycle, so the task stays locked to a fixed rate regardless of how long each iteration took, as long as it finishes within the period.
Interview question: How does a context switch work on a Cortex-M RTOS?
Answer: When a switch is needed, the kernel pends the PendSV exception, which runs at the lowest priority once no other interrupt is active. On exception entry the hardware has already stacked R0 to R3, R12, LR, PC and xPSR on the current task's process stack. The PendSV handler pushes R4 to R11 (and the upper FPU registers if used), saves the PSP into the current task's control block, selects the next task, loads its saved PSP, pops R4 to R11, and returns with an EXC_RETURN value that makes the hardware unstack the rest and resume the new task.
Build it: prove the pump meets its deadlines
This is step 2 of the module project. Marketing wants Bluetooth added to the pump. Before anyone writes that code, the team must show that the dosing task will still always finish in time with one more task competing for the CPU. Testing cannot prove that; response-time analysis can.
Lab: Response-time analysis for the pump's tasks
Each task has a worst-case execution time C, a period T and a deadline equal to its period. Tasks are given in priority order, highest first (rate monotonic: the shorter the period, the higher the priority).
utilisation_pct(tasks, n)returns the total CPU load, the sum ofC / T, as a whole percentage rounded down (compute it with integers:sum of C * 10000 / T, then divide by 100).response_time(tasks, n, i)returns the worst-case response time of taski: the time from its release until it finishes, when every higher-priority task (0toi - 1) is released at the same moment. Start withR = C_iand repeatR = C_i + sum over j < i of ceil(R / T_j) * C_juntilRstops changing. IfRever exceeds the task's deadlineT_i, stop and return -1.schedulable(tasks, n)returns true when every task meets its deadline.
ceil(a / b) for positive integers is (a + b - 1) / b.
Going deeper
Interview question: How would you show a drone's attitude loop always meets its deadline?
Answer: Measure each task's worst-case execution time on the target, assign priorities by rate, and do response-time analysis including interrupts and blocking on shared resources, with margin. Then monitor deadlines at run time (a check that each loop iteration starts on time) and test under worst-case load.
Interview question: What is jitter in a periodic task and how do you reduce it?
Answer: Jitter is the variation in when each instance of a periodic task actually starts or finishes, caused by higher-priority tasks and interrupts running first and by critical sections. Reduce it by giving the task a high priority, keeping higher-priority work and critical sections short, using vTaskDelayUntil, and moving the timing-critical part (sampling, output updates) into a timer interrupt or hardware trigger.
Interview question: How do you measure the worst-case execution time of a task?
Answer: Instrument it with the cycle counter (DWT->CYCCNT) or a GPIO toggle observed on a logic analyser, run it under worst-case inputs and conditions (cache misses, maximum interrupt load) and record the maximum over long runs, then add margin. Static WCET analysis tools give safe upper bounds for certification. RTOS trace tools show each task's execution time and preemptions.
Explain it: In your own words, explain rate-monotonic scheduling and what its utilisation bound tells you.
Answer: Rate-monotonic scheduling gives each periodic task a fixed priority according to its period: the shorter the period, the higher the priority. For tasks whose deadlines equal their periods, it is the best possible fixed-priority assignment. The utilisation bound says that if the total fraction of CPU time the tasks need, the sum of each execution time divided by its period, is below n times (2 to the power 1/n minus 1), about 69 to 83 percent depending on n, every deadline is guaranteed to be met. Above the bound it may still work, but you must check with response-time analysis.