Context switch

Switching from one process to another requires a certain amount of time for doing the administration – saving and loading registers and memory maps, updating various tables and lists, etc.

What is actually involved in a context switch depends on the architectures, operating systems, and the number of resources shared (threads that belong to the same process share many resources compared to unrelated non-cooperating processes).

For example, in the Linux kernel, context switching involves loading the corresponding process control block (PCB) stored in the PCB table in the kernel stack to retrieve information about the state of the new process.

CPU state information including the registers, stack pointer, and program counter as well as memory management information like segmentation tables and page tables (unless the old process shares the memory with the new) are loaded from the PCB for the new process.

This negatively affects performance because every memory reference to the TLB will be a miss because it is empty after most context switches.

This context switch can be triggered by the process making itself unrunnable, such as by waiting for an I/O or synchronization operation to complete.

The handler may save additional context, depending on details of the particular hardware and software designs.

This is usually stored in a data structure called a process control block (PCB) or switchframe.

In doing so, the program counter from the PCB is loaded, and thus execution can continue in the chosen process.

This operation as there are sequential reads and writes and there's no waits for function calls used, hence no context switch/wait takes place in this case.

Then, the hardware switches to kernel mode and jumps into interrupt handler for the operating system to take over.

When a task switch occurs the CPU can automatically load the new state from the TSS.

As with other tasks performed in hardware, one would expect this to be rather fast; however, mainstream operating systems, including Windows and Linux,[11] do not use this feature.