What is Context Switching?

Switching the CPU to another process by saving the current state of a running process in PCB. And loading the saved state from PCB for a new process is called context switching.

It is a complementary part of a multitasking operating system because multitasking is also happens through it. 

The following information is stored for later use in PCB when the process is switched.

  • Process ID
  • Process State
  • Pointer
  • Priority
  • PC
  • CPU Registers
  • I/O information
  • Accounting Information

The above information is the context of the Process.

Switching Steps

  • 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 PCB of 2nd process by changing the state to running in PCB.
  • Update the memory management data if required.
  • After the execution of the second process, restore the context of the first process on the CPU.

When does switching occur?

The main reasons why switching occurs are given below

Problems with Switching

The main factors that lead 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 there is no need for flushing of TLB.

Is User and kernel mode switching context switching?

The 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 a different concept. However, depending on the OS, a context switch may also take place at the time of the user and kernel mode transition.