RTOS fundamentals
Hard and soft real time, tasks, states, and FreeRTOS versus Zephyr.
What "real time" means
A real-time system is one where a correct answer delivered late is a wrong answer. It is about predictability, not speed: the system must always meet its deadlines, including in the worst case.
| Hard real time | Firm real time | Soft real time | |
|---|---|---|---|
| Missed deadline | System failure | Result useless, but no harm | Quality degrades |
| Examples | Airbag, motor commutation, pacemaker | Video frame decode, sensor sample that arrives too late | UI responsiveness, audio streaming with buffering |
Why use an RTOS
A super loop with interrupts (see the code patterns guide) works well for small systems. It becomes hard to manage when:
- work items have very different time scales (a 50 µs control loop, a 10 ms sensor read, a 2 s network transaction) and a slow one delays a fast one
- code must wait for things (a network reply, a flash erase) without blocking everything else
- several independent activities need to be developed and tested separately
An RTOS (real-time operating system) kernel lets you split the program into tasks (also called threads), each written as a simple sequential loop that blocks while waiting, and schedules them by priority so the most urgent ready task always runs.
The costs: a kernel in flash (5 to 20 KB), a separate stack per task in RAM, context-switch overhead, and a new class of bugs (races, deadlocks, priority inversion).
Tasks and their states
void sensor_task(void *arg) {
for (;;) {
int32_t t = read_temperature();
xQueueSend(readings, &t, 0);
vTaskDelay(pdMS_TO_TICKS(100)); /* block: other tasks run meanwhile */
}
}
xTaskCreate(sensor_task, "sensor", 256, NULL, 2, NULL);
vTaskStartScheduler(); /* never returns */
Each task has a priority, a stack and a state:
| State | Meaning |
|---|---|
| Running | Executing on the CPU (one task per core) |
| Ready | Able to run, waiting for the CPU |
| Blocked | Waiting for an event: a delay, a queue, a semaphore, a notification; uses no CPU |
| Suspended | Explicitly taken out of scheduling |
A well-designed system spends most of its time with every task blocked and the idle task running (which can put the CPU to sleep).
The kernel's services
| Service | Use |
|---|---|
| Delays and timers | Periodic work, timeouts |
| Queues | Pass data between tasks, and from ISRs to tasks |
| Semaphores | Signal events; count resources |
| Mutexes | Protect shared resources, with priority inheritance |
| Event groups / flags | Wait for one or several conditions |
| Task notifications | Lightweight direct signalling to one task |
| Memory pools | Deterministic allocation |
FreeRTOS versus Zephyr
The two most common open-source choices take different approaches:
| FreeRTOS | Zephyr | |
|---|---|---|
| Scope | A kernel (plus optional libraries: TCP, MQTT, OTA) | A full OS: kernel, drivers, device tree, networking, Bluetooth, file systems, shell |
| Size | Very small (a few KB) | Larger; configurable |
| Configuration | FreeRTOSConfig.h | Kconfig and device tree, like Linux |
| Drivers | You bring them (vendor HAL) | Built-in driver model across many vendors |
| Build | Any build system | CMake + west tool |
| Licence | MIT | Apache 2.0 |
| Typical use | Small MCUs, products built on a vendor SDK | Connected devices, multi-vendor portability |
Others you will meet: Azure RTOS ThreadX (now Eclipse ThreadX), embOS, SAFERTOS and VxWorks or QNX (certified or high-end), RT-Thread, NuttX (POSIX-like), and Arm's CMSIS-RTOS API, which wraps several kernels behind one interface.
Sizing stacks
Each task needs its own stack, sized for its deepest call chain plus local variables plus the context saved on a switch (and on an interrupt, if interrupts use the task stack). Too small corrupts memory silently; too large wastes RAM.
- Start generously, then measure: FreeRTOS's
uxTaskGetStackHighWaterMark()reports the minimum free space ever seen. - Enable stack-overflow checking during development (
configCHECK_FOR_STACK_OVERFLOW), and use the MPU to guard stacks where available. - Avoid large local arrays and
printfwith floating point in small tasks; both use a lot of stack.
The program below shows the idea of watermarking: fill a stack with a known pattern, run, then see how much was overwritten.
#include <stdio.h>
#include <stdint.h>
#define STACK_WORDS 64
static uint32_t stack[STACK_WORDS];
int main(void) {
for (int i = 0; i < STACK_WORDS; i++) stack[i] = 0xA5A5A5A5u; /* paint at task creation */
/* Pretend the task ran and its deepest call used the top 23 words (stacks grow down). */
for (int i = STACK_WORDS - 23; i < STACK_WORDS; i++) stack[i] = (uint32_t)i;
int untouched = 0;
while (untouched < STACK_WORDS && stack[untouched] == 0xA5A5A5A5u) untouched++;
printf("high-water mark: %d of %d words never used (%d bytes spare)\n",
untouched, STACK_WORDS, untouched * 4);
return 0;
}
Pitfall: Calling a blocking RTOS function (
vTaskDelay,xQueueReceivewith a timeout) from an interrupt handler, or a non-FromISRAPI, corrupts the scheduler. ISRs use only the...FromISRvariants and never block.
Interview question: When would you use an RTOS instead of a super loop?
Answer: When the system has several activities with different timing requirements that interfere in a single loop, when code needs to wait on slow operations (network, storage, user interaction) without stalling time-critical work, when priorities must be enforced (a control loop must preempt logging), or when the codebase is large enough that independent tasks with clear interfaces simplify development. A super loop is better for small, simple systems where its determinism, lower RAM use and lack of concurrency bugs outweigh the benefits.
Interview question: How do you choose a stack size for an RTOS task?
Answer: Estimate from the deepest call path (static analysis with -fstack-usage or a tool), add locals, the saved context and interrupt frames if they use the task stack, and a margin. Then measure at run time by stack painting or the kernel's high-water-mark function, under worst-case conditions, and enable overflow detection and an MPU guard region during development. Avoid large stack arrays and heavy library calls such as printf with floats in small tasks.
Build it: the pump's task scheduler
This is step 1 of the module project, the firmware of an insulin pump. The pump runs several jobs at different rates: reading the glucose sensor, driving the dosing motor, updating the display. Before using a real RTOS, build the heart of one: a scheduler that decides, every millisecond tick, which task runs.
Lab: A tick-driven, priority-based task scheduler
The task table is provided: each task has a period in ticks (1 tick = 1 ms), a priority (a higher number is more urgent) and a function. Every task is due for the first time at tick 0.
sched_tick()is called by the 1 ms timer interrupt. It advances the time by one tick (the first call makes it tick 1) and marks each task whose period has come round as ready. A task that is still ready from its last period has missed its deadline: count one miss for it (it stays ready, and runs once).sched_dispatch()is called by the main loop. It runs every ready task, highest priority first, clearing each one's ready flag before calling it, and returns how many it ran.sched_misses(i)returns taski's miss count.
sched_init() marks every task ready at tick 0 and clears the counters. An idle main loop calls sched_dispatch() after every tick; the checks also play a main loop that falls behind.
Going deeper
Interview question: How would you split a smart speaker's firmware into RTOS tasks?
Answer: By deadline and responsibility: a high-priority audio task fed by DMA, a wake-word detection task, a network task for Wi-Fi and streaming, and a low-priority user-interface task, communicating through queues. Give each a measured stack size, keep shared data behind clear ownership, and verify the audio deadline holds while everything else is busy.
Interview question: What does it mean for an RTOS to be deterministic?
Answer: That its services have bounded, predictable execution times, such as the time to switch tasks, to give a semaphore or to respond to an interrupt, independent of how many tasks or objects exist, so worst-case response times can be calculated. Data structures like per-priority ready lists and sorted delayed lists exist for this. It does not mean fast; it means predictable.
Interview question: How do you choose task priorities in a new design?
Answer: Assign priorities by deadline urgency rather than importance: shorter deadlines and periods get higher priorities (rate-monotonic or deadline-monotonic). Keep the number of levels small, put interrupt-driven, time-critical work in the highest tasks, background work such as logging lowest, and make sure every task blocks so lower ones run. Validate with timing measurements or response-time analysis.
Explain it: In your own words, explain the four task states in an RTOS and what moves a task between them.
Answer: A running task is the one executing on the CPU. Ready tasks could run but are waiting for the CPU because a higher or equal priority task is running. A blocked task is waiting for something, such as a delay to expire, a semaphore, a queue message or a notification, and uses no CPU until that event happens, when it becomes ready. A suspended task has been explicitly removed from scheduling until resumed. The scheduler always runs the highest-priority ready task, so a task becoming ready can preempt the running one.