← Lessons

quiz vs the machine

Silver1080

Concurrency

The Cooperative Coroutines

Tasks that voluntarily hand control back at yield points instead of being interrupted.

4 min read · intro · beat Silver to climb

Cooperation instead of interruption

In cooperative scheduling a running task keeps the CPU until it chooses to give it up. A coroutine is a function that can pause itself at a yield point, return control to a scheduler, and later resume exactly where it stopped, with its local state intact.

Why this is cheap

  • There is no kernel involved, so switching between coroutines is just a function return and a jump.
  • Switches happen only at known yield points, so the task author controls exactly where pauses can occur.
  • Because nothing interrupts at an arbitrary instruction, many shared data races simply cannot happen between yields.

The catch

The model relies on every coroutine being polite. If one coroutine runs a long loop without ever yielding, it starves every other coroutine on that thread. Nothing can force it to stop. This is why cooperative systems insert yield points around input, output, and other natural waiting moments.

Key idea

Cooperative coroutines switch only at explicit yield points, making switches cheap and races rare, but a task that never yields can starve all the others.

Check yourself

Answer to earn rating on the learn ladder.

1. When does a cooperative coroutine give up the CPU?

2. What is the main risk of cooperative scheduling?