- Whenever an interrupt arrives, the CPU must to a state-save of currently running process, then switch into kernel mode to handle the interrupt, and the do a state-restore of the interrupted process.
- Context switch happens when
- the time slice for one process has expired and a new process is to be loaded from the ready queue.
- This will be instigated by a timer interrupt, which will then cause the current process’ state to be saved and the new process’s state to be restored.
- Saving and restoring states involves saving and restoring all registers and program counter(s), as well as the process control blocks.
- Context switch happens VERY VERY frequently, and the overhead of doing the switching is just lost CPU time, so context switches (state saves and restores) need to be as fast as possible. Some hardware has specific provisions for speeding this up, such as a single machine instruction for saving or storing all registers at once.
- The Operating System needs to store a copy of the CPU registers to memory.
- When it is time for the processor to give up the processor so another process can run, it needs to save it’s current state.
- Equally, we need to be able to restore this state when the process is given more time to run on the CPU. To do this the operating system needs to store a copy of the CPU registers to memory.
- When it is time for the process to run again, the operating system will copy the register values back from memory to the CPU registers and the process will be right back where it left off.