RTOS & Real-Time Concepts · Interview question

How does a context switch work on a Cortex-M specifically?

A strong answer

Cortex-M makes it efficient using two stack pointers and a dedicated exception. Tasks run using the Process Stack Pointer (PSP) while the kernel and interrupt handlers use the Main Stack Pointer (MSP), which keeps task stacks separate from interrupt stack usage. On any exception entry the hardware automatically stacks eight registers, R0-R3, R12, LR, PC, and xPSR, onto the current stack, so half the context is saved for free. The actual switch is performed in the PendSV exception handler: the RTOS port manually saves the remaining registers (R4-R11) onto the outgoing task's PSP, stores that stack pointer in the outgoing task's TCB, loads the incoming task's stack pointer from its TCB, restores its R4-R11, and does an exception return, at which point the hardware automatically unstacks the other eight registers and the new task runs. PendSV is deliberately configured at the lowest exception priority so a requested switch happens only after all higher-priority interrupts have finished, meaning you never switch tasks in the middle of an ISR. A switch is triggered either by the SysTick tick handler (when the scheduler finds a different highest-priority ready task) or directly by an ISR that unblocks a higher-priority task (e.g., giving a semaphore), which pends PendSV so the switch occurs on interrupt exit.

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

Context Switching

How the kernel pauses one task and resumes another: saving and restoring CPU registers to each task's own stack, on Cortex-M via PendSV, PSP/MSP, and hardware auto-stacking.

More Context Switching questions

Browse all 472 interview questions
How does a context switch work on a Cortex-M specifically? | EmbeddedPrep.io