Course contentsShow
← Linux
Lesson 461 of 1,8195. Process Management and SignalingFree lesson

Execution Context and Context Switching

Describe how the kernel pauses and resumes thread execution to maintain multi-tasking illusions.

In this lesson, you will learn how the Linux kernel juggles multiple active tasks by saving and restoring the "state" of a process so it can pause and resume execution seamlessly.

The Illusion of Parallelism

Even if your CPU has only one core, Linux creates the illusion that dozens of programs are running at once. It achieves this by rapidly switching between different threads. An execution context is essentially a "snapshot" of a process at a specific moment in time. It includes the contents of the CPU registers, the instruction pointer (which tells the CPU which line of code to execute next), and the stack pointer (which tracks local variables and function calls).

The Mechanics of a Context Switch

When the kernel decides it is time to switch tasks—perhaps because a process’s time slice has expired or it is waiting for input—it performs a context switch. Think of this like a teacher pausing a student mid-sentence, having them write down exactly where they left off, and then inviting another student to take the desk.

The process follows these steps:

  1. Saving: The kernel saves the current CPU register values into the process's thread_struct (stored in the process's kernel stack).
  2. Switching: The kernel updates the memory management unit (MMU) to point to the new process's memory address space.
  3. Restoring: The kernel loads the saved register values of the next process from its respective structure, effectively "injecting" its state back into the CPU.

A Conceptual View

While the kernel does this in highly optimized assembly code, you can visualize the state the kernel tracks like this:

struct execution_context {
    unsigned long ip;    // Instruction Pointer (where we are)
    unsigned long sp;    // Stack Pointer (our local data)
    unsigned long ax;    // General purpose registers
    // ... saved state for a thread
};

Because this happens thousands of times per second, the CPU appears to be performing many tasks simultaneously. By saving this context, the kernel ensures that when a thread is "resumed," it has no idea it was ever interrupted; it simply picks up exactly where it left off, maintaining the integrity of the multi-tasking environment.

Key Takeaway: A context switch is the kernel’s way of freezing a process's CPU state so that it can pause one task and perfectly resume another without losing any data or progress.