Definition
Process Switch
A process switch (or context switch) is the operation where the operating system pauses the execution of the currently running process and transfers control to another process.
This mechanism is central to multitasking, as it allows the CPU to be shared among multiple processes, maintaining the “illusion of parallelism.”
A mode switch is a prerequisite for a process switch.
Mechanism
The operating system is triggered to perform a process switch when it gains control of the CPU. This occurs through three primary mechanisms:
- Supervisor Call (or System Call): An explicit request by the running program for an OS service (e.g., I/O).
- Trap: An exception generated by the current instruction (e.g., division by zero or a memory access violation).
- Interrupt: A signal from an external source (e.g., a timer timeout or I/O completion) that is handled by an interrupt handler.
The OS then performs the following sequence:
- Save Context: Store the Program Counter, Stack Pointer, and Registers of the current process into its PCB.
- Update State: Change the process state to Ready or Blocked in the Process Table.
- Select Next: The OS scheduler chooses the next process from the Ready queue.
- Memory Switch: Update the memory management unit (e.g., Page Directory Base Register), which typically flushes the TLB.
- Restore Context: Load the hardware context from the new process’s PCB into the CPU.
- Resume Execution: The CPU begins executing instructions from the new process’s saved program counter.
Visual Representation
Performance Overhead
A process switch is a “pure overhead” operation, as the CPU performs no useful user-level work during the transition.
Cost
Process switching is expensive primarily due to the memory switch. Invalidating caches (like the TLB) causes a significant performance penalty on subsequent memory accesses as the hardware must fetch page translations from main memory.
The time required also depends on:
- Hardware support (number of registers to save/restore).
- Operating system efficiency in managing the Process Table.