Context Switching in Operating System (original) (raw)

Last Updated : 20 Sep, 2025

Context switching is the process where the CPU stops running one process, saves its current state, and loads the saved state of another process so that multiple processes can share the CPU effectively.

Need in Multitasking

It is essential in multitasking systems where many processes need CPU time.

Role in Scheduling

Context Switching Triggers

Context Switching Happen:

When switching between user mode and kernel/user mode is necessary, operating systems use the kernel/user switch.

Working Process of Context Switching

Let us take examples of two processes **po and **p1 that execute in interleaved manner

1223

State Diagram of Context Switching

**Explanation of the Above Diagram

The diagram illustrates how the CPU alternates execution between two processes — p0 and p1 — through context switching.

1. Execution Phase (Process p0)

2. Saving Current State (p0 → PCB0)

3. Loading New Process State (PCB1 → p1)

4. Execution Phase (Process p1)

5. Saving State of p1 (p1 → PCB1): The OS saves the current state of p1 into PCB1.

6. Reloading State of p0 (PCB0 → p0)

Overhead

Factors Affecting Switch Time

Context-switch times are highly dependent on hardware support. For example, some processors (such as the Sun UltraSPARC) provide multiple sets of registers. In this case, a context switch simply requires changing the pointer to the current register set. However, if there are more active processes than available register sets, the system resorts to copying register data to and from memory, as before. Additionally, the more complex the operating system, the greater the amount of work that must be done during a context switch.