What is context switching and what happens during one?
A context switch is the process by which the RTOS saves the state of the currently running task and restores the state of the next task to run. The "context" includes the CPU registers (general-purpose registers, program counter, stack pointer, status register), and on Cortex-M processors also the floating-point registers if an FPU is present.
The typical sequence is: (1) an interrupt or system call triggers the scheduler; (2) the scheduler determines the next task to run based on priority; (3) the current task's register set is pushed onto its own stack; (4) the stack pointer is switched to the new task's stack; (5) the new task's registers are popped from its stack; (6) execution resumes at the new task's saved program counter.
On ARM Cortex-M, the hardware automatically saves a subset of registers (R0–R3, R12, LR, PC, xPSR) on exception entry, and the RTOS kernel manually saves the remaining registers (R4–R11, and optionally S16–S31 for FPU). The PendSV exception is typically used to perform the actual switch at the lowest interrupt priority, ensuring it does not preempt other ISRs. Context switch time is a critical RTOS metric — it is typically 5–20 microseconds on a Cortex-M4 running at 100 MHz, depending on FPU usage and stack depth.
Source: Operating Systems & RTOS Q&A
