What is a context switch, and why is it considered overhead?
MediumConceptProcesses & Threads
Answer
A context switch happens when the OS stops the running process or thread, saves its state (program counter, registers and stack pointer) into its PCB, and loads the saved state of another one so the CPU continues that one instead. It is triggered by a timer interrupt, a blocking system call such as a disk read, or a higher-priority process becoming ready.
- It is pure overhead: no useful user work is done while state is saved and restored, typically a few microseconds per switch.
- A switch between processes also changes the address space. That may flush the TLB (the cache of address translations) and leaves the CPU caches "cold", so the new process runs slowly at first.
- A switch between threads of the same process is cheaper, because the memory mappings stay the same.
Example: assume each switch costs 0.1 ms. With a 10 ms time slice, the overhead is 0.1 / (10 + 0.1) ≈ 1% of CPU time. With a 1 ms slice, it becomes 0.1 / (1 + 0.1) ≈ 9%. This is why the time quantum in Round Robin must be much larger than the switch time. Analogy: placing a bookmark in one book before picking up another, then finding your place again later.
More in Processes & Threads
| # | Problem | Platform | Difficulty | Open | 1st1st Visit | 2nd2nd Visit | RevRevise |
|---|---|---|---|---|---|---|---|
| 1 | What is the difference between a process and a thread? | Concept | Easy | Read the answer to What is the difference between a process and a thread? | |||
| 2 | What are the states of a process, and what is a PCB? | Concept | Easy | Read the answer to What are the states of a process, and what is a PCB? | |||
| 3 | What is a context switch, and why is it considered overhead? | Concept | Medium | Read the answer to What is a context switch, and why is it considered overhead? | |||
| 4 | What does fork() do, and what does it return? | Concept | Medium | Read the answer to What does fork() do, and what does it return? | |||
| 5 | What are zombie and orphan processes? | Concept | Medium | Read the answer to What are zombie and orphan processes? |