The trigger is usually an interrupt, an ISR (say a UART RX) gives a semaphore that unblocks a high-priority task. Inside the ISR the kernel notices a higher-priority task is now Ready and requests a context switch, but the switch itself doesn't happen in the ISR body; on Cortex-M the kernel sets the PendSV exception pending. PendSV is configured at the lowest interrupt priority, so it only fires once all higher-priority ISRs have finished (tail-chaining into it), which is exactly what you want, the actual task switch runs when the CPU is otherwise about to return to thread mode. When PendSV runs, the handler saves the outgoing task's context (the core auto-stacks R0-R3, R12, LR, PC, xPSR on exception entry; the handler manually pushes the remaining callee-saved R4-R11, and on an FPU part the S-registers if used) onto that task's own stack, saves the updated stack pointer into its TCB, then loads the incoming task's saved SP and pops its context, and returns, so execution resumes in the new task exactly where it left off. This is why each task needs its own stack and why the switch is O(1): it's just a swap of stack pointers plus register save/restore. Deferring the switch to PendSV also keeps the actual ISRs short and ensures a switch never happens in the middle of a higher-priority interrupt still being serviced.
RTOS & Real-Time Concepts · Interview question
When a higher-priority task becomes Ready, what actually happens at the hardware level to switch to it on a Cortex-M?
A strong answer
What a weak answer sounds like
You know the answer. Do you know what gets you dinged?
Pro breaks down the answer most candidates actually give to this question — and the specific reason an interviewer marks it down. It’s the difference between sounding correct and sounding senior, on all 472 questions.
From the lesson
Preemptive vs Round-Robin Scheduling
How the scheduler chooses: priority preemption (urgent runs first), round-robin time-slicing among equal priorities, and cooperative scheduling, plus the starvation and fairness tradeoffs.
More Preemptive vs Round-Robin Scheduling questions
What's the difference between preemptive and cooperative scheduling?Two tasks have the same priority and both are ready. What happens?What is starvation and how do you prevent it?How does FreeRTOS combine priority and round-robin scheduling?When is cooperative scheduling actually a good choice?Under preemptive priority scheduling, can a high-priority task ever be blocked by a low-priority one?
Browse all 472 interview questions