Home / Learn Chip Programming / RTOS Tasks, Scheduling and Context Switches

RTOS Tasks, Scheduling and Context Switches

How the kernel decides which task runs and what a context switch costs.

In shortHow the kernel decides which task runs and what a context switch costs.

Theory in plain words

Task statesReadyRunningBlockedSuspendedscheduler
Task states

What it is

Each task has a priority, a state (running, ready, blocked, suspended) and its own stack. The scheduler picks the highest-priority ready task. Equal priorities share time (round robin). A context switch saves registers and restores another task's.

Why we use it

Priority mistakes cause starvation and priority inversion. Stack mistakes cause crashes. Understanding states is the base of all RTOS work.

How it works

Tick interrupt (1 ms) checks for blocked tasks that timed out and for higher priority tasks; PendSV performs the switch on Cortex-M.

Where it is used

  • Designing task structure
  • Debugging "task never runs"
  • Interview questions

Round robin and priority scheduler

Gantt chart of three tasksTry it Yourself

Equal priority tasks share time slices; a higher priority ready task always runs first.

FreeRTOS task basics
void led_task(void *arg) { for (;;) { toggle_led(); vTaskDelay(pdMS_TO_TICKS(500)); } }   // blocks 500 ms, lets others run
xTaskCreate(led_task, "led", 128, NULL, 2, NULL);        // stack in words, priority 2
vTaskStartScheduler();                                  // never returns
// vTaskSuspend / vTaskResume / vTaskDelete / uxTaskGetStackHighWaterMark(NULL) for stack checks
Careful:A task must never return from its function (delete it or loop forever). And every task needs enough stack: check the high-water mark during testing.

Quick quiz

1. Highest priority ready task...

2. What does vTaskDelay do?