← Lessons

quiz vs the machine

Gold1350

Concurrency

Coroutines and Cooperative Scheduling

Functions that suspend and resume under cooperative control.

5 min read · core · beat Gold to climb

Coroutines and Cooperative Scheduling

A coroutine is a function that can suspend its execution and later resume from exactly where it left off, keeping its local state intact. Unlike a normal function that runs to completion, a coroutine yields control voluntarily.

This is the heart of cooperative scheduling. In a cooperative scheduler, a running task keeps the processor until it chooses to yield. The scheduler only switches tasks at well defined suspension points such as an await or a yield. Contrast this with preemptive scheduling, where the runtime can interrupt a task at any instant.

Consequences of cooperation:

  • Cheap context switches Suspending a coroutine saves only a small frame, not a full kernel thread, so millions can coexist.
  • Predictable critical sections Between two yield points the task runs uninterrupted, so some data races vanish.
  • Starvation risk A task that never yields, perhaps stuck in a tight loop, blocks every other task on that thread.

Coroutines power async runtimes. An await suspends the coroutine, registers a callback, and frees the thread to run other ready coroutines until the awaited result arrives.

The discipline required is that long running work must yield often, otherwise the cooperative promise of fairness breaks.

Key idea

Coroutines suspend and resume on purpose, letting a cooperative scheduler run many tasks cheaply as long as each one yields.

Check yourself

Answer to earn rating on the learn ladder.

1. When does a cooperative scheduler switch tasks?

2. What is the main risk of cooperative scheduling?

3. Why are coroutine context switches cheap?