Operating System - Context Switch
What is Context Switching?
Context switching is the procedure of storing the context or state of a process so that it can be reloaded when required and execution can be resumed from the same point as earlier. This is a feature of a multitasking operating system and allows a single CPU to be shared by multiple processes
What Happens During a Context Switch
The OS performs these steps:
-
Save the current process's context (registers, program counter, stack pointer, etc.) in its PCB (Process Control Block).
-
Load the context of the next scheduled process from its PCB.
-
Resume execution of the new process.
Diagram: Context Switch
Let us consider a scenario where context switch occurs from process P0 to process P1. The steps that occur are depicted in the following diagram .
As we can see from the diagram, two context switches occur here. The first context switch causes a switch from process P0 to P1. We can see that process P0 is initially executing. A system call or interrupt occurs that requests P0 to be pre-empted from its executing state so that process P1 may execute. In order to do so, context switching takes place. In order to keep the partial results of execution of P0, the state of P0 is saved in its process control block, PCB0. The state of process P1 is reloaded to the CPU from its PCB1. Thus, P0 goes to an idle state, which P1 starts executing. In the second context switch, the reverse procedure occurs, whereby the state of process P1 is saved in PCB1 and the saved state of P0 is loaded from PCB0.