The idea: one CPU, four devices, four program shapes

A small microcontroller often has to serve several devices at once: bytes arrive on a UART, a user presses a button, a sensor must be read every 10 ms, a display must be redrawn now and then. There is one CPU, so the program needs a plan for who runs when. David E. Simon's An Embedded Software Primer sorts these plans into four architectures, from the simplest to the most powerful: round-robin, round-robin with interrupts, function-queue scheduling and a real-time operating system (RTOS). The page builds the same device all four ways and feeds each one exactly the same events. Then it measures the response time of every event: from the moment it happens to the moment its handler has finished.

Four code shapes side by side. Round-robin: a while loop that polls uart_rx_ready, button_pressed, sensor flag and display flag in turn and calls each handler. Round-robin with interrupts: ISRs copy the byte or set flags, the same loop tests the flags. Function queue: ISRs put a handler pointer in a priority queue, main takes the first entry and calls it. RTOS: ISRs give a semaphore, four tasks wait on their semaphores, and the kernel runs the highest-priority ready task. Below each: the UART worst case, sum of all handlers, sum of all handlers, longest handler, almost zero
Each step moves more of the decision "what runs next" out of a fixed loop and into priorities: first in the ISRs, then in a queue, then in a kernel that can preempt.

The device and its events

Each kind of event has a handler: the task code that does the real work. Interrupt service routines (ISRs) and task switches take a few microseconds, so the page counts them as 0 ms and draws them as red ticks.

eventhandlertimepriority
a byte on the UARTUART_Handler (parse the byte)1 ms1 (most urgent)
a button edgeButton_Handler2 ms2
sensor timer, every 10 msSensor_Read3 ms3
display timer, every 50 msDisplay_Update8 ms (20 ms in the slow trace)4 (least urgent)

The standard trace has the sensor timer at 0, 10, …, 60 ms, the display timer at 0 and 50 ms, the button at 0 and 33 ms and UART bytes at 1, 24 and 54 ms. The UART is the device that matters most: if its handler is slow, the other side of the link waits, and bytes can be lost.

Round-robin: a super loop that polls

while (1) {
    if (uart_rx_ready())      UART_Handler();
    if (button_pressed())     Button_Handler();
    if (sensor_timer_flag())  Sensor_Read();
    if (display_timer_flag()) Display_Update();
}

There are no interrupts. The loop asks each device in turn whether it needs service, reading a status bit in a hardware register. It is the simplest program there is, and it has no shared-data problems, because only one piece of code ever runs. But a device is seen only when the loop reaches its check. In the worst case an event comes just after its check and waits for every other handler: here 2 + 3 + 8 = 13 ms, plus its own 1 ms. In the standard trace the byte at 1 ms comes just after the loop checked the UART at 0 ms, then waits while Button_Handler, Sensor_Read and Display_Update run from 0 to 13 ms: response 13 ms (Demo: round-robin super loop: UART 13, button 2, sensor 12, display 13 ms). Adding a handler makes every other one slower, so the timing changes every time the code changes.

Polling can also lose data. A UART receive register holds one byte. When the next byte arrives before the loop has read the first, the hardware sets an overrun error (ORE on an STM32) and the new byte is gone (Demo: a UART burst, polling loses bytes: the bytes at 6, 7 and 8 ms all arrive while the byte from 1 ms still waits, and all three are lost).

Round-robin with interrupts

volatile bool fButton, fSensor, fDisplay;
void USART1_IRQHandler(void) { rx_buf[rx_head++ % N] = USART1->DR; }
void EXTI0_IRQHandler(void)  { fButton = true; }
...
while (1) {
    while (rx_head != rx_tail) UART_Handler();   /* one byte each */
    if (fButton)  { fButton = false;  Button_Handler(); }
    if (fSensor)  { fSensor = false;  Sensor_Read(); }
    if (fDisplay) { fDisplay = false; Display_Update(); }
}

Each device now has an ISR that does the urgent part at once: the UART ISR copies the byte out of the register into a ring buffer, and the others set a flag. Many people call this foreground/background: ISRs in the foreground, the loop in the background. The ISRs have hardware priorities among themselves, and no byte is lost any more (Demo: a UART burst: the bytes at 6, 7 and 8 ms are saved and handled from 14 to 17 ms, each 9 ms after it came). But the handlers still run in the loop's fixed order, so their response is exactly as bad as with polling (Demo: round-robin with interrupts: the same 13, 2, 12, 13 ms). The price is shared data: the ISR and the loop both touch the flags and the buffer, so they must be volatile, and code that reads and clears them must disable interrupts for a moment. A bool flag also merges two events into one: with a 20 ms display redraw, the sensor ticks at 20 and 60 ms find fSensor still set, and those two samples are lost (Demo: a 20 ms display redraw). A counter instead of a bool would keep them.

Function-queue scheduling

void USART1_IRQHandler(void) { save_byte(); queue_put(UART_Handler, 1); }
void TIM2_IRQHandler(void)   { queue_put(Sensor_Read, 3); }
...
while (1) {
    void (*f)(void) = queue_get_highest();   /* waits while the queue is empty */
    f();
}

Now the ISRs do not set flags: each one puts a pointer to its handler into a queue sorted by priority, and the loop always calls the most urgent entry next. The UART no longer waits behind every handler, only behind the one that is already running, because a handler still runs to its end. So its worst case is the longest handler plus its own time: 8 + 1 = 9 ms. In the standard trace the byte at 1 ms is handled at 2 ms, right after Button_Handler, but the byte at 54 ms comes 1 ms after Display_Update started and waits until 61 ms: 8 ms (Demo: function-queue scheduling: UART 8, button 2, sensor 7, display 14 ms). Every ISR queues an entry, so nothing is lost. The weak spot is the longest handler: make Display_Update take 20 ms and the UART worst case grows to 20 ms (Demo: a 20 ms display redraw). Low-priority entries can also wait for a long time if urgent ones keep coming.

An RTOS with priorities

void USART1_IRQHandler(void) { save_byte(); xSemaphoreGiveFromISR(uartSem, &woken); portYIELD_FROM_ISR(woken); }
void UartTask(void *p) {                 /* priority 4, the highest of the four */
    for (;;) { xSemaphoreTake(uartSem, portMAX_DELAY); UART_Handler(); }
}
/* ButtonTask, SensorTask, DisplayTask the same, with priorities 3, 2, 1 */

Each handler becomes a task with its own stack and a priority. A task waits on a semaphore; the ISR gives it, and the RTOS kernel switches at once to the highest-priority task that is ready, even if a lower one is in the middle of its work. That is preemption. The UART task never waits for another handler: every byte is done 1 ms after it arrives, in every trace (Demo: RTOS with priorities). The button task is preempted by the byte at 1 ms (3 ms instead of 2). The cost lands on the least urgent task: Display_Update is interrupted by sensor reads and bytes and its worst case grows to 17 ms (20 ms in the burst, 38 ms with the 20 ms redraw). A new low-priority task does not change the response of the high-priority ones, which makes an RTOS the most stable design when the code grows. FreeRTOS numbers its priorities upwards (a bigger number is more urgent); the page's "priority 1" is the most urgent.

The rest of the cost is in the code. The kernel takes flash (FreeRTOS says about 6–12 KB on a typical port), each task needs its own stack in RAM, and any data that two tasks share must be protected with a mutex, because a task can now be stopped between any two instructions. With a mutex comes priority inversion; see priority ceiling and SRP and real-time scheduling and priority inversion. Whether every task meets its deadline can be checked on paper with rate-monotonic analysis, or with earliest-deadline-first priorities.

Worst-case response, side by side

Bar chart of the UART handler's worst response on the page's traces. Standard trace: round-robin 13 ms, round-robin with interrupts 13 ms, function queue 8 ms, RTOS 1 ms. Slow display trace: 25, 25, 20 and 1 ms. Next to each, the bound: sum of all handlers, sum of all handlers, longest handler plus its own, its own time
A longer display handler hurts the first three designs, because the UART can wait behind it; under the RTOS the byte preempts it and stays at 1 ms.
traceround-robinwith interruptsfunction queueRTOS
standard13 ms, 0 lost13 ms, 0 lost8 ms1 ms
UART burst13 ms, 3 bytes lost ✗13 ms, 0 lost8 ms1 ms
20 ms display25 ms, 3 lost ✗25 ms, 2 sensor ticks lost ✗20 ms1 ms

Choosing one

Simon's advice is to pick the simplest architecture that meets the response requirements. Many products are a round-robin loop with a few ISRs; an RTOS pays off when there are many tasks with different deadlines, or when the program will keep growing.

architectureprioritiesworst response of task codewhen code changescode cost
round-robinnonesum of all handlersevery handler slows the otherssmallest: one loop, no ISRs
round-robin with interruptsISRs by hardware priority; handlers nonesum of all handlers (plus ISR time)good for ISRs, poor for handlers+ ISRs and data shared with them
function queueISRs, then handlers by prioritylongest handler (plus ISR time)fairly good+ a priority queue of function pointers
RTOSISRs, then tasks by priority, with preemptionISR time + task switchvery good+ kernel (a few KB), a stack per task, mutexes

See also a time-triggered co-operative scheduler, a round-robin with one timer interrupt that flags tasks from a table, and the cyclic executive, which fixes at design time what runs in every frame.

See also interrupt priorities and nesting for what happens inside the "0 ms" ISR ticks of this page, and button debounce as a state machine for a button handler that a super loop can call every 10 ms.

See also preemptive vs cooperative scheduling on a general-purpose OS, the game loop and its fixed timestep, a super loop of another kind, and the watchdog timer that resets a loop that has hung.

See also MCU startup from power-on to main() for the startup code that runs before the super loop or RTOS starts.

What the page leaves out

ISRs, the polling checks and task switches take 0 ms here; on a real chip each costs microseconds, and Simon's bounds add the time of all ISRs to every task's response. Handler times are fixed; real ones depend on the input, so the worst-case execution time must be measured. The page does not show interrupt latency and nesting, disabling interrupts around shared data (which delays the ISRs), a full ring buffer, an RTOS's tick interrupt, time slicing between equal priorities, mutexes and priority inheritance, stack sizing, or low-power sleep in the idle loop. The traces are short and chosen by hand; a real worst case must be found by analysis, not by one test run.

On the mind map

Open the Operating Systems mind mapOperatingSystemsBoot and program start: from power on to main()Boot and program startProcesses and the kernel: how user code talks to the kernelProcesses and the kernelInterrupts and devices: hardware interrupts the CPUInterrupts and devicesScheduling and deadlock: who runs next, who gets whatScheduling and deadlockVirtual memory: every address is translatedVirtual memoryPhysical memory: who gets which bytes of RAMPhysical memoryFiles and storage: from open() down to the diskFiles and storageDisks and RAID: blocks down to platter or flashDisks and RAIDIsolation and security: limit what a process can doIsolation and securityContext switchContext switchswitch_mm loads CR3, switch_to swaps stacksCPU scheduling algorithmsCPU scheduling algorithmsFCFS, SJF, RR, CFS: compare waiting timeMultiprocessor SchedulingMultiprocessor SchedulingPer-CPU queues + stealing beat one lockMulti-Level Feedback QueueMulti-Level Feedback QueueUse your quantum, drop a levelLottery & strideLottery & strideTickets set shares; stride runs lowest passPreemptive vs cooperativePreemptive vs cooperativetimer forces a switch, or wait for yieldReal-time schedulingReal-time schedulingpriority inversion, fixed by inheritanceRate-monotonic analysisRate-monotonic analysisShort period = high priority; RTA decidesPriority ceiling and SRPPriority ceiling and SRPOne lower critical section, no deadlockEDF vs Least SlackEDF vs Least SlackEDF: any set with U ≤ 1; overload dominoesTime-triggered schedulerTime-triggered schedulerISR only flags; super loop runs, then sleepsCyclic executiveCyclic executivea timer runs a fixed frame tableSuper loop to RTOSUART worst: 13, 13, 8, 1 msLoad averageLoad averagedamped count of R and D tasksBanker's algorithmBanker's algorithmgrant only if a safe order still existsDeadlock detectionDeadlock detectionFind the cycle, then kill a victimOpen the Operating Systems mind mapOperating Systemswho runs next, who gets whatScheduling and deadlockContext switchContext switchswitch_mm loads CR3, switch_to swaps stacksCPU scheduling algorithmsCPU scheduling algorithmsFCFS, SJF, RR, CFS: compare waiting timeMultiprocessor SchedulingMultiprocessor SchedulingPer-CPU queues + stealing beat one lockMulti-Level Feedback QueueMulti-Level Feedback QueueUse your quantum, drop a levelLottery & strideLottery & strideTickets set shares; stride runs lowest passPreemptive vs cooperativePreemptive vs cooperativetimer forces a switch, or wait for yieldReal-time schedulingReal-time schedulingpriority inversion, fixed by inheritanceRate-monotonic analysisRate-monotonic analysisShort period = high priority; RTA decidesPriority ceiling and SRPPriority ceiling and SRPOne lower critical section, no deadlockEDF vs Least SlackEDF vs Least SlackEDF: any set with U ≤ 1; overload dominoesTime-triggered schedulerTime-triggered schedulerISR only flags; super loop runs, then sleepsCyclic executiveCyclic executivea timer runs a fixed frame tableSuper loop to RTOSUART worst: 13, 13, 8, 1 msLoad averageLoad averagedamped count of R and D tasksBanker's algorithmBanker's algorithmgrant only if a safe order still existsDeadlock detectionDeadlock detectionFind the cycle, then kill a victim
This page on the Operating Systems mind map · 78 pages in 9 branches · open it to see the whole map and test yourself in recall mode.