← Lessons

quiz vs the machine

Gold1340

Concurrency

The Preemptive Scheduling

How a timer interrupt lets the scheduler forcibly take the CPU from any running task.

4 min read · core · beat Gold to climb

The scheduler takes control

Under preemptive scheduling, the scheduler can forcibly suspend a running task even if it never asked to yield. A hardware timer interrupt fires at regular intervals, handing control to the scheduler, which may save the current task's state and run a different one. The task does not cooperate; it is simply paused.

Why systems use it

  • Fairness since no single task can hog the CPU, because its time slice expires.
  • Responsiveness as a long computation cannot freeze the whole system.
  • No trust needed because tasks need not be written to yield politely.

The cost it brings

The price is that a switch can happen at any instant, even in the middle of updating shared data. This is exactly why concurrent code needs locks or atomics: a task may be paused with a half finished update, and another task could observe the inconsistent state. Preemption also adds the overhead of saving and restoring full task state on every time slice.

Key idea

Preemptive scheduling uses timer interrupts to forcibly switch tasks, guaranteeing fairness and responsiveness but forcing concurrent code to guard shared data against switches at any moment.

Check yourself

Answer to earn rating on the learn ladder.

1. How does a preemptive scheduler regain control from a running task?

2. Why does preemption force concurrent code to guard shared data?