Context Switch - aryanjoshi0823/5143-Operating-System GitHub Wiki
Context switching is the process of saving the context (or state) of a running process so that it can be resumed later from the same point. This mechanism is essential in multitasking operating systems, enabling multiple processes to share a single CPU.
Components of a Process Context
The context of a process includes:
- Process stack
- Memory address space
- Virtual memory address space
- Register values
- Stack Pointer (SP)
Context Switching Triggers:
Context switching can be triggered by three major events:
-
Multitasking
- In multitasking environments, the CPU switches from one process to another.
- The scheduler saves the state of the current process and loads the state of the next process.
-
Interrupt Handling
- Interrupts automatically trigger a partial context switch to minimize handling time.
- The hardware performs this switch for rapid response.
-
User and Kernel Mode Switching
- When transitioning between user mode and kernel mode, the operating system performs a context switch.
Steps in Context Switching:
The context switching process involves the following steps:
- Save the context of the currently running process.
- Update the Process Control Block (PCB) and relevant fields of the outgoing process.
- Move the PCB to the appropriate queue (e.g., ready queue, I/O queue).
- Select the next process to execute.
- Update the PCB of the incoming process, setting its state to
running
. - Restore the context of the incoming process by loading its PCB and register values.
Example of Context Switching
Consider a scenario where the system switches from process P0
to process P1
:
-
Switch from
P0
toP1
:- Save the state of
P0
in its PCB (PCB0
). - Load the state of
P1
from its PCB (PCB1
). P0
transitions to an idle state, andP1
starts executing.
- Save the state of
-
Switch back from
P1
toP0
:- Save the state of
P1
inPCB1
. - Reload the saved state of
P0
fromPCB0
. P1
transitions to an idle state, andP0
resumes execution.
- Save the state of