Backend
Backend Essentials
Why Context Switching?

Why did Context Switching come into the picture?

In modern computing, we are accustomed to having Spotify, a Node.js server, Docker, and 50 Google Chrome tabs open simultaneously. It feels like the computer is running all of these processes at the exact same time.

However, because of CPU Sequential Execution, we know that a single CPU core can physically only run one instruction stream at a given exact millisecond.

The Hardware Disparity

The core problem that necessitates Context Switching is a simple numbers game:

The number of active Processes vastly outnumbers the number of physical CPU cores.

The Example:

Imagine a standard developer laptop:

  • Physical Hardware: 4 CPU Cores
  • Active Processes: 100 running applications (Background services, Node.js, databases, browser)

Because there are only 4 physical cores, the CPU is physically incapable of running all 100 applications simultaneously. At any exact given millisecond, 96 applications are sitting completely idle, frozen in RAM, waiting for a CPU core to become available.

The Solution: Rapid Context Switching

To prevent your computer from freezing and only allowing you to open 4 apps at a time, the Operating System steps in as the master scheduler.

Instead of letting one process hog a CPU core until it finishes, the OS gives a process a tiny "time slice" (e.g., 10 milliseconds).

Once that time slice is up, the OS:

  1. Pauses the current process.
  2. Saves its exact state (by saving the memory address in the Program Counter).
  3. Loads the state of the next process in the queue.
  4. Resumes execution for the next process.

The OS performs this "Switch" thousands of times per second across all 4 cores. Because the CPU operates so incredibly fast, human users cannot perceive the pauses. It creates the perfect illusion of multitasking (Concurrency), even though the CPU is still strictly executing tasks sequentially.