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.
Theory in plain words
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
Equal priority tasks share time slices; a higher priority ready task always runs first.
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 checksQuick quiz
1. Highest priority ready task...
The scheduler always picks it.
2. What does vTaskDelay do?
Other tasks may run.