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:

  1. 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.
  2. Interrupt Handling

    • Interrupts automatically trigger a partial context switch to minimize handling time.
    • The hardware performs this switch for rapid response.
  3. 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:

  1. Save the context of the currently running process.
  2. Update the Process Control Block (PCB) and relevant fields of the outgoing process.
  3. Move the PCB to the appropriate queue (e.g., ready queue, I/O queue).
  4. Select the next process to execute.
  5. Update the PCB of the incoming process, setting its state to running.
  6. 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:

  1. Switch from P0 to P1:

    • Save the state of P0 in its PCB (PCB0).
    • Load the state of P1 from its PCB (PCB1).
    • P0 transitions to an idle state, and P1 starts executing.
  2. Switch back from P1 to P0:

    • Save the state of P1 in PCB1.
    • Reload the saved state of P0 from PCB0.
    • P1 transitions to an idle state, and P0 resumes execution.