Multithreading – Why Threads Use a Stack in Context Switches

multithreadingoperating systems

Correct me if I'm wrong, but if I have an operating system that makes a context switch, then that context switch is in practice a switch from one thread to another, where one thread was running one task and then switches to another task and the reason the threads needs a stack is to save the variables of the task to be able to return to its saved state.

Is my understanding correct of what a context switch does or did I misunderstand?

Best Answer

The stack has nothing to do with multi-threading. The stack saves information about a subroutine. When I say sub-routine, I am not speaking about any particular language, but the process of making a call to another area of the program space, and returning from that area when finished. When making the call, the currently executing routine may be using registers. Those register values must be saved in a stack, so that the called routine can use those registers. This is greatly simplified, but the general idea is the stack saves the context of the caller, and the stack grows larger as the call chain grows deeper.

If you have multiple threads, each one needs a stack, since they are all executing at the same time. The context switch allows you to have more threads than CPU cores. It allows multiple threads to share one core by pre-empting the execution of a thread, and starting another thread.