The kernel saves the entire CPU state of the running task and restores the saved state of the task that's switching in, so each resumes exactly where it left off. The "context" is the set of registers that define what the task is doing: the general-purpose registers, the program counter (the next instruction), the stack pointer, the status/flags register, the link register, and the FPU registers if the task uses floating point. Mechanically, the kernel pushes the outgoing task's registers onto that task's own stack, records the task's resulting stack pointer in its task control block, then loads the incoming task's stack pointer from its TCB and pops its registers back off its stack, after which execution continues in the new task as if it had never been paused. So a context switch is fundamentally "save registers to the old task's stack, switch stacks, restore registers from the new task's stack." The reason each task needs its own stack is precisely so its context and call frames have a private place to be preserved across switches.
RTOS & Real-Time Concepts · Interview question
What exactly happens during a context switch?
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
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.