What is Context Switching?
Switching the CPU to another process by saving the current state of running process in PCB. And loading the saved state from PCB for new process is called context switching.
It is a complementary part of a multitasking operating system because multitasking is also happens through it.
When the process is switched, the following information is stored for later use in PCB.
- Process ID
- Process State
- CPU Registers
- I/O information
- Accounting Information
Above information’s are context of Process.
- Save the context of running (First) in PCB.
- Place the PCB of the next(2nd) process, which has to execute, into the relevant queue i.e. ready queue, I/O queue etc.
- Select a new (2nd) process for execution.
- Update the the PCB of 2nd process by changing the state to running in PCB.
- Update the memory management data if required.
- After the execution of second process, restore the context of the first process on CPU.
When does switching occur?
The main reasons due to which switching is occur are given below
- Due to Trap or Interrupt.
- Higher priority process arrives (CPU scheduling Algorithm).
Problems with Switching
Main factors due to which it leads to an overhead are
- TLB flushes
- sharing the cache between multiple tasks
- execution of task scheduler etc.
Note: Context switching in-between the threads of the a process is faster than in-between the different processes.Because threads have the same virtual memory maps and there is no need of flushing of TLB.
Is User and kernel mode switching is context switching?
Answer is No. When the control of CPU is transfer in-between user mode and kernel mode in OS then context switching is not necessary.Because context switching and User, kernel modes are different concept . However, depending on the OS, context switch may also take place at the time of user and kernel mode transition.