Operating System Design/Processes/Context Switch

Context switching is the procedure of storing the state of an active process for the CPU when it has to start executing a new one. For example, process A with its address space and stack is currently being executed by the CPU and there is a system call to jump to a higher priority process B; the CPU needs to remember the current state of the process A so that it can suspend its operation, begin executing the new process B and when done, return to its previously executing process A.

Context switches are resource intensive and most operating system designers try to reduce the need for a context switch. They can be software or hardware governed depending upon the CPU architecture.

Context switches can relate to either a process switch, a thread switch within a process or a register switch. The major need for a context switch arises when CPU has to switch between user mode and kernel mode but some OS designs may obviate it.

A common approach to context switching is making use of a separate stack per switchable entity (thread/process), and using the stack to store the context itself. This way the context itself is merely the stack pointer. For example,

pusha                        ;push all registers
mov OLD_ESP, SAVED_LOCATION
mov NEW_ESP, esp
popa

here the act of context switching is done by changing the stack pointer to a new location, and the registers are stored on the stack itself.