Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 37 ยท RTOS and Scheduling

What Is an RTOS? Tasks, Ticks and Real-Time

Learn what a real-time operating system does, why a super loop stops scaling, how tasks, priorities and the scheduler tick work, and how FreeRTOS-style code is organized.

A small embedded program starts life as a single endless loop: read inputs, compute, write outputs, repeat. This super loop (also called "bare metal" or "foreground/background" design, with interrupts as the foreground) is simple, fast, and enough for many products. But as features pile up (a display, a network link, a motor controller, a user interface) the loop turns into a tangle of flags and timing hacks, and one slow job delays everything else.

A real-time operating system (RTOS) solves this by letting you write each job as its own task (a function with its own stack and priority) and giving you a scheduler that decides which task runs when. "Real-time" does not mean "fast": it means the system meets its deadlines predictably. This lesson explains what an RTOS provides, when you need one, and how its core ideas (tasks, states, ticks and priorities) fit together.

The problem with a super loop

Imagine a loop that must blink an LED every 50 ms while it also reads a slow sensor that takes 40 ms each time. In a super loop the blink code can only run between the other jobs, so the LED blinks late whenever the sensor read is in progress. The simulation below counts how late.

C Why one slow job hurts everything in a super loop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The blink is supposed to be 50 ms apart, but every other blink comes about 20 ms late, because a sensor read was in progress when it fell due. You could chop the sensor read into small steps (the cooperative scheduler lesson shows how), or use an interrupt, but each fix adds complexity. An RTOS makes the structure explicit: the blink task and the sensor task are independent, and the scheduler interrupts the low-priority sensor task whenever the high-priority blink task is due.

What an RTOS gives you

  • Tasks (threads). Independent functions, each with its own stack. A task typically contains an infinite loop that waits for something, does work, and waits again.
  • A scheduler. Chooses the running task. Most RTOSes use fixed-priority preemptive scheduling: the highest-priority ready task always runs, and it preempts a lower-priority one the moment it becomes ready.
  • Timing services. Delays (vTaskDelay), absolute periodic waits (vTaskDelayUntil), software timers and a system tick.
  • Synchronization and communication. Queues, semaphores, mutexes, event flags and notifications (the next lessons cover these).
  • Memory services. Static or dynamic allocation of task stacks and objects, with predictable allocators.

What an RTOS is not: it does not make code faster, and it is much smaller than Linux. It has no virtual memory, usually no file system unless you add one, and it may run on a chip with 16 KB of RAM. Popular choices are FreeRTOS, Zephyr, Azure RTOS ThreadX, RT-Thread, embOS, RTEMS and Micrium uC/OS.

Hard, firm and soft real-time

  • Hard real-time: missing a deadline is a failure with serious consequences (airbag deployment, anti-lock brakes, pacemaker pulses).
  • Firm real-time: a late result is useless but not dangerous (a dropped video frame).
  • Soft real-time: a late result is less valuable but still usable (updating a display).

The important property is determinism: you can bound how long each operation takes, even in the worst case. That is why RTOS code avoids unbounded loops, general-purpose malloc, and long periods with interrupts disabled.

Task states

Every task is in exactly one state at any moment, and the scheduler moves it between them.

stateDiagram-v2
    [*] --> Ready: created
    Ready --> Running: highest priority ready task is chosen
    Running --> Ready: preempted by a higher-priority task, or time slice ends
    Running --> Blocked: waits for delay, queue, semaphore or event
    Blocked --> Ready: delay expires or the event arrives
    Running --> Suspended: suspended explicitly
    Suspended --> Ready: resumed

Only one task per CPU core is Running. A Blocked task costs no CPU time.

The state that matters most is Blocked. A well-designed task spends almost all its life blocked, waiting for a delay or a message, so the CPU is free for others. A task that busy-waits (while (!flag) {}) never blocks and starves everything below its priority.

The tick and the context switch

The RTOS configures a hardware timer to interrupt at a fixed rate, typically 1 kHz. This is the tick. On each tick the kernel updates the time, wakes tasks whose delay has expired, and may decide that a different task should now run. Switching tasks means saving the current task's CPU registers (its context) on its own stack and loading another task's registers. On Cortex-M this is done in a low-priority interrupt (PendSV) so the switch never delays real hardware interrupts.

Each task has a task control block (TCB) that stores its state, priority, stack pointer, and delay counter. Stack sizing is a classic source of crashes: each task needs enough room for its deepest call chain, local arrays and the saved context. A task that overflows its stack corrupts a neighbor's memory in a way that looks like random bugs.

This program is a miniature kernel: three tasks with priorities, a tick that wakes delayed tasks, and a scheduler that always runs the highest-priority task that is ready. Each task does a few ticks of "work" and then sleeps. A letter in the timeline is the task that ran during that tick, and a dot means the idle task ran.

C A miniature preemptive scheduler

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Read the timeline. H runs in the very tick it wakes (every fifth tick), even when M or L is in the middle of its work: that is preemption. The interrupted task keeps its remaining work (work_left) and resumes later, which is exactly what saving and restoring a context achieves in a real kernel. The dots show times when no task was ready and the idle task ran; real systems put the CPU to sleep there to save power (see low-power design).

What task code looks like

A FreeRTOS task is an ordinary function with an infinite loop. This is a read-only example, since it needs the FreeRTOS kernel and a board:

C
// Read-only: FreeRTOS on a microcontroller
void vBlinkTask(void *pvParameters) {
    TickType_t lastWake = xTaskGetTickCount();
    for (;;) {
        toggle_led();
        vTaskDelayUntil(&lastWake, pdMS_TO_TICKS(50));   // exact 50 ms period
    }
}

int main(void) {
    board_init();
    xTaskCreate(vBlinkTask, "blink", 128, NULL, 2, NULL);   // stack in words, priority 2
    xTaskCreate(vSensorTask, "sensor", 256, NULL, 1, NULL);
    vTaskStartScheduler();                                   // never returns
}

vTaskDelayUntil takes an absolute wake time, so the period does not drift by the task's own run time, just as last += period did in the software timer lesson.

When to use an RTOS

An RTOS is a good fit when you have several independent activities with different timing needs, a networking or USB stack that expects threads, or a team that needs clear module boundaries. It costs flash, some RAM (stacks add up), and new bug classes such as deadlock and priority inversion. For a device with two simple jobs, a super loop with a timer interrupt is usually better. Choose the smallest tool that meets the deadlines.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does 'real-time' mean in an RTOS?

    Real-time is about determinism and meeting deadlines, not raw speed.
  2. 2. In a fixed-priority preemptive scheduler, a high-priority task becomes ready while a low-priority task runs. What happens?

    The highest-priority ready task always runs; the lower one returns to Ready and resumes later.
  3. 3. Why should a task usually spend most of its time in the Blocked state?

    Tasks wait for delays or events instead of spinning, so the CPU can run others or sleep.
  4. 4. What is stored in a task's TCB?

    The task control block holds what the kernel needs to manage and switch the task.

Summary

  • A super loop is simple but one slow job delays all the others; an RTOS gives each job its own task, stack and priority.
  • Fixed-priority preemptive scheduling always runs the highest-priority ready task; the tick wakes delayed tasks.
  • Tasks move between Ready, Running, Blocked and Suspended; good tasks block while waiting instead of spinning.
  • Real-time means predictable deadlines, not speed; use an RTOS only when its structure pays for its cost.

Next: A Cooperative Scheduler