🧠 What is a Context Switch?

A Context Switch is the process of saving the state of the current running process and loading the state of another process so that it can run on the CPU.

This allows multiple processes or threads to share a single CPU core as if they’re running in parallel (preemptive multitasking).


🧩 When Does Context Switching Happen?

ScenarioExample
🕒 Time slice expiresRound Robin scheduler
Process blocksWaiting for I/O
🆕 Higher priority process arrivesPreemption
🏁 Process terminatesCPU assigned to next
🔁 System call / interruptSwitching between user ↔ kernel mode

📦 What is Saved and Restored?

During a context switch, the OS swaps:

ComponentWhy It’s Needed
🧠 Program Counter (PC)To resume from the correct instruction
🪢 CPU RegistersVariables and intermediate values
🧵 Stack PointerLocal function data
📄 Memory Maps(optional, if switching between processes)
📜 Process Control Block (PCB)Stores all of the above and more metadata

For thread context switches, memory is usually shared — so only registers, stack, and PC are saved.


⚙️ How It Works (Simplified)

[ Running Process: P1 ]
↓ (Context switch triggered)
→ Save P1 state to PCB
→ Load P2 state from PCB
↑
[ Running Process: P2 ]

The CPU is never idle — it’s just rapidly switching between tasks.


⏱️ Is Context Switching Free?

No. It has cost.

Cost ComponentWhy
🧠 Save/restore registersCPU cycles
🔁 Flush/load cachesCPU cache may be invalidated
🧮 TLB missesMay need to reload virtual memory mappings
💰 OverheadCan be 1–100+ microseconds depending on hardware

Excessive context switching leads to CPU thrashing — too much time spent switching, not enough computing.


🎯 Process vs Thread Context Switch

AspectProcess SwitchThread Switch (same process)
📦 Memory switchYes (address space changes)No (shared memory)
💰 CostHigherLower
📚 ExampleSwitching from Chrome to VS CodeSwitching between UI and network thread in Chrome

🧠 Interview-Ready Definition:

A Context Switch is the OS operation that saves the state of a currently running process or thread and loads the state of the next one to run, enabling multitasking on a single CPU. It incurs overhead due to state saving, memory/cache flushing, and TLB updates.


🧠 Real-World Analogy

Imagine a teacher (CPU) calling students (processes) to the board one by one.
Before a new student comes up, the current one has to save their notes, and the new one loads theirs before continuing. That pause is the context switch.