Context Switching
Context Switching
Introduction
Context switching in operating systems and CPU management, is a concept that deals with how the CPU shifts from process/thread to another. Context here refers to the state of the process. Below I will write process but it can be applied for both processes and threads.
The state is usually in a struct of the following :
- Program counter (PC) - the address of the next instruction to execute.
- CPU registers
- Memory management information (like page tables in virtual memory systems).
During a switch all these are saved into PCB (process control block) struct. It is stored in the memory of the process being switched out so that it can be restored when the scheuler calls the process again.
The PCB is a data structure in the operating system which contains all the information about a process. This includes:
- Process ID
- Process state (e.g., running, waiting, ready)
- Program Counter
- CPU registers (saved values)
- Memory management information
- CPU scheduling information (priority, time slice, etc.)
- I/O status information
- Accounting information (CPU time used, etc.)
Triggering a Context Switch
- Time slice expiration in time-sharing systems (when a process’s time quantum is up). This is for schedulers that implement algo’s like Round Robin for process management.
- I/O requests or interrupts (like waiting for disk I/O).
- Higher priority process becoming ready (preemptive scheduling).
Saving the context
- The current state of the running process is saved into the memory. This includes:
- Saving the contents of all CPU registers into the PCB of the process being switched out.
- Saving the program counter and other control information.
Loading New Context
- Load New State:
- The context of the new process to be executed is loaded into the CPU:
- The CPU registers are restored from the PCB of the new process.
- The program counter is set to where the new process was last interrupted.
- The context of the new process to be executed is loaded into the CPU:
Overheads
- Overhead:
- Context switching introduces overhead due to:
- Time taken to save and load state from memory.
- Potential cache flushing if the new process uses different pages.
- TLB (Translation Lookaside Buffer) flushes in virtual memory systems.
- Context switching introduces overhead due to:
- Optimization:
- Modern OSes try to minimize this overhead through techniques like:
- Using hardware support for quick state saving (like special registers for context storage).
- Reducing unnecessary switches by using efficient scheduling algorithms.
- Modern OSes try to minimize this overhead through techniques like:
This post is licensed under CC BY 4.0 by the author.