Linux CPU Context Switch Deep Dive

How much do you know about CPU context switch?

Geek Culture
Published in
8 min readJan 20, 2022


We all know that Linux is a multitasking OS, which supports simultaneous running of tasks far greater than the number of CPUs. Of course, these tasks are not actually running at the same time (Single CPU), but because the system assigns the CPU to tasks in turn for a short period of time, it creates the illusion of multiple tasks running at the same time.

CPU Context

Before each tasks runs, CPU needs to know where to load and start the task. This means the system needs to help set up CPU registers and program counters in advance.

CPU registers are small but extremely fast memory built into the CPU. The program counter is used to store the position of the instruction being executed by the CPU, or the position of the next instruction to be executed.

They are all dependent environments that the CPU must rely on before running any tasks, so they are also called “CPU contexts”. Like the following graph shows:

Knowing what a CPU context is, I think it’s easy for you to understand CPU context switching. “CPU context switching” is to first save the CPU context (CPU registers and program counters) of the previous task, then load the context of the new task to these registers and program counter, and finally jump to the new location pointed to by the program counter.

These saved contexts are stored in the system kernel and loaded again when the task is rescheduled for execution. This ensures that the original state of the task is not affected, and the task appears to be running continuously.

CPU Context Switching Types

You may say that CPU context switching is nothing more than updating CPU registers and program counters values, and these registers are designed to run tasks quickly, then why does it affect the CPU performance?

Before answering this question, let me ask, have you ever thought about what these “tasks” are? You may say that a task is a process, or a thread. Yes…