80/20 Of The Week … What Actually Happens During a Context Switch?
You can have Chrome open, a game running, some music playing and a Spring Boot app doing its thing in the background, and it all looks like it is happening at the same time.
Ignore hyper-threading for a second since that is a topic for another time hehe. One logical CPU is actually executing one thread at a particular moment, while the operating system makes the rest feel simultaneous by switching between threads stupidly fast.
That switch needs the CPU to remember where it left off. A thread has an instruction pointer which says what to execute next, a stack pointer, registers holding temporary values and processor status. Together, that is part of its execution context.
Say a thread is handling a request in your backend. Its time slice ends, it waits for a database response or a higher-priority task needs the CPU. The kernel saves the thread’s relevant state, marks it runnable or waiting, then the scheduler chooses another runnable thread.
It roughly looks like this.
save Thread A -> choose next runnable thread -> restore Thread B -> continue
Once Thread B’s state is restored, the CPU continues it from its own next instruction as if it had never been paused. A few moments later, Thread A may get its turn again and carry on with the request.
That is why blocking on I/O is different from burning CPU time. While a thread waits for the network, disk or database, the core can do useful work for another thread. If every thread is doing heavy calculations, there is much less to hide behind the switching.
The switch is useful, but it is not free. The scheduler does work, CPU caches may no longer contain the data needed by the next thread and switching between processes can also disturb address-translation caches such as the TLB. Too many runnable threads can therefore make a system busier without making it faster, which is a very annoying way to lose performance.
The exact state saved depends on the CPU architecture and operating system, but the basic story stays the same… pause one execution context, keep enough information to return later, then restore another one.
TLDR
Multitasking works because the OS repeatedly freezes and resumes execution contexts. It is great for responsiveness and waiting on I/O, but switching itself has a cost, so more threads does not automatically mean more work gets done.
