In this lesson, you will learn how the processor physically swaps the "mental state" of one task for another during a context switch.
The Anatomy of a Switch
When an RTOS decides to switch from Task A to Task B, the processor cannot simply jump to the new code. If it did, Task B would begin using the registers currently holding Task A’s data, leading to instant corruption. To prevent this, the kernel must perform an atomic swap of the CPU's state.
A context switch is essentially a "save-the-world" operation followed by a "load-the-world" operation. Every processor has a set of core registers: the Program Counter (PC), Stack Pointer (SP), Status Register, and general-purpose registers (R0–Rn). The kernel treats these as a snapshot of the task’s progress.
The Swap Sequence
- Saving Context: When a timer interrupt triggers the scheduler, the processor automatically pushes some registers onto Task A’s stack. The kernel then manually pushes the remaining registers. The current Stack Pointer is saved into Task A’s Task Control Block (TCB).
- Scheduling: The kernel identifies that Task B is the next highest priority task.
- Restoring Context: The kernel loads the Stack Pointer from Task B’s TCB. It then "pops" the saved registers from Task B’s stack back into the physical hardware.
Consider this pseudo-assembly representation of the final transition step:
; Task A is currently running
PUSH {R4-R11} ; Save remaining registers to Task A's stack
STR SP, [TaskA_TCB] ; Save Task A's stack pointer to its TCB
LDR SP, [TaskB_TCB] ; Load Task B's stack pointer into SP
POP {R4-R11} ; Restore Task B's saved registers
BX LR ; Return to Task B's execution address
By pointing the SP to Task B’s stack, the processor is tricked into thinking it has been "interrupted" from Task B all along. When the POP instructions execute, they populate the CPU with Task B’s data. The BX LR (Branch Exchange) finally pushes the saved Program Counter onto the execution pipeline, and Task B resumes exactly where it left off, completely unaware it was ever paused.
Key Takeaway: A context switch is the process of saving the CPU register set onto the current task's stack, updating the stack pointer to a different task's memory, and popping the new task's register state into the processor hardware.