mediumConceptEntryMidSenior
What actually happens during a context switch, and why should an application developer care?
A context switch in an operating system saves one thread's CPU state, runs the scheduler and restores another thread. Application developers care because excessive switches add latency through cache and TLB disruption, lock contention and oversized thread pools. It also connects scheduling to the point an interviewer is testing.
5 min readUpdated 2026-08-15
Answer
Short answer
During a context switch, the kernel saves registers and the program counter for the outgoing thread, chooses the next runnable thread, then restores that thread's state. The expensive part is often the cache and TLB disruption after the switch, not the register save itself.
Was this answer helpful?
Likely follow-ups
- Why does an oversized thread pool often make a CPU-bound service slower rather than faster?
- How does a blocking mutex differ from a spinlock in terms of context switches, and when is spinning the better choice?
- What does the operating system have to do differently when a thread is rescheduled onto a different physical core?
- How would you tell from production metrics whether a service is suffering from involuntary preemption or from blocking on I/O?
Related questions
- Two threads write to adjacent counters and throughput collapses. What is happening and how do you fix it?hardAlso on concurrency and cpu-cache5 min
- Process versus thread: what is the difference? Give me one real example and one mistake people make about it.easyAlso on threads and context-switch4 min
- What belongs inside an interrupt service routine, and what must be kept out of it?mediumAlso on concurrency5 min
- A flash sale decrements stock from many threads. Do you go optimistic or pessimistic, and how do you prove nothing oversold?mediumAlso on concurrency5 min