Computing Library › Real Time Systems
Real Time Systems

Context Switching

A context switch saves one task's processor state and restores another's; its cost and predictability directly affect real-time timing budgets.

Switching Between Tasks

A context switch is the operation of saving the complete processor state of the currently running task and restoring that of another, so multiple tasks can share one processor. The saved state includes the register file, program counter, stack pointer, and status flags, and may include floating-point and vector registers. Switching happens when the scheduler preempts a task or when a task blocks.

The Cost

Kronos motion — confinement time

The direct cost is the time to save and restore registers, typically small and bounded. The larger and less predictable cost is indirect: after a switch, the new task often runs with cold caches and a flushed pipeline, so its early execution is slower until the working set is reloaded. This cache-related cost is variable and is one reason context switches complicate worst-case timing.

Why It Matters for Real Time

Every preemption in a schedule implies context-switch overhead. Schedulability analysis must include this overhead, usually by adding it to each task's execution time or accounting for it at each preemption point. Frequent switching among many tasks raises overhead and cache pressure, which is one argument for keeping the number of high-frequency tasks small.

Reducing and Bounding Switch Cost

Threads Versus Processes

Switching between threads that share an address space is cheaper than switching between processes, which additionally requires changing the memory-management context and can flush address-translation caches. Real-time designs often keep cooperating real-time work in one address space to minimize this cost, isolating only untrusted or non-critical components into separate protection domains where the added switch cost is acceptable.