🧠 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?
| Scenario | Example |
|---|---|
| 🕒 Time slice expires | Round Robin scheduler |
| ⏳ Process blocks | Waiting for I/O |
| 🆕 Higher priority process arrives | Preemption |
| 🏁 Process terminates | CPU assigned to next |
| 🔁 System call / interrupt | Switching between user ↔ kernel mode |
📦 What is Saved and Restored?
During a context switch, the OS swaps:
| Component | Why It’s Needed |
|---|---|
| 🧠 Program Counter (PC) | To resume from the correct instruction |
| 🪢 CPU Registers | Variables and intermediate values |
| 🧵 Stack Pointer | Local 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 Component | Why |
|---|---|
| 🧠 Save/restore registers | CPU cycles |
| 🔁 Flush/load caches | CPU cache may be invalidated |
| 🧮 TLB misses | May need to reload virtual memory mappings |
| 💰 Overhead | Can 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
| Aspect | Process Switch | Thread Switch (same process) |
|---|---|---|
| 📦 Memory switch | Yes (address space changes) | No (shared memory) |
| 💰 Cost | Higher | Lower |
| 📚 Example | Switching from Chrome to VS Code | Switching 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.