← Lessons

quiz vs the machine

Gold1430

Concurrency

Cooperative Versus Preemptive Scheduling

Two ways to decide when one task yields the processor to another, and the tradeoffs of each.

5 min read · core · beat Gold to climb

Who decides when to switch

A scheduler must decide when a running task gives up the processor so another can run. There are two philosophies. In cooperative scheduling the task itself yields at chosen points. In preemptive scheduling an outside force interrupts the task whether it likes it or not.

Cooperative scheduling

Here tasks run until they voluntarily pause, typically at an await or an explicit yield.

  • Switches happen only at known yield points, so shared state is safe between them.
  • A task that never yields can hog the processor and starve others.
  • It is lightweight, since no forced interruption machinery is needed.

The event loop is fundamentally cooperative; a long synchronous callback blocks everything.

Preemptive scheduling

Here a timer or the operating system interrupts tasks at arbitrary moments.

  • Switches can happen anywhere, so no single task can monopolize the processor.
  • Shared state needs locks because a switch may occur mid update.
  • It guarantees fairness and responsiveness even with misbehaving tasks.

Key idea

Cooperative scheduling switches only at voluntary yield points and risks one task hogging the processor, while preemptive scheduling interrupts anywhere for fairness at the cost of needing locks on shared state.

Check yourself

Answer to earn rating on the learn ladder.

1. When does a switch happen under cooperative scheduling?

2. What is the main risk of cooperative scheduling?

3. Why does preemptive scheduling need locks on shared state?