Operating Systems

What is Context Switching?

Context switching is the process by which the operating system stops the execution of one process and allows another process to execute on the CPU.

Image illustrating how context switching works, when switching between two processes.
Image illustrating how context switching works, when switching between two processes.

When Process A stops executing, its current execution state must be preserved. This includes values such as its:

  • CPU registers
  • program counter
  • stack pointer
  • other relevant CPU state

The operating system saves this state in process-management structures associated with Process A, including its Process Control Block (PCB). The scheduler can then select Process B. If Process B has previously executed, its saved context is restored into the CPU. The CPU can then continue executing Process B from where it previously stopped.

As discussed earlier in the "Introduction to resource allocation" tutorial, the medium-term scheduler determines which processes should be temporarily suspended and which suspended processes should be allowed to return to active execution.

Why does context switching happen?

A context switch can occur for several reasons. For example, the running process may use up its allocated time slice, become blocked waiting for I/O, be preempted by a higher-priority process, or voluntarily give up the CPU. The important idea is that a context switch does not restart the process. Because its execution context was saved, the process can later continue from where it stopped.

Context switching has a cost

During the context switch, the CPU is spending time saving/restoring state and running operating-system scheduling code rather than executing the processes' useful application instructions. So context switching introduces overhead. Operating systems therefore need to balance switching frequently enough to provide responsiveness and CPU sharing without switching so frequently that excessive CPU time is spent performing context switches.