liveBook · Manning

Coroutine

As explained in The Coder Cafe

A coroutine is a suspendable and resumable computation that cooperatively switches execution with other computations, often within a single thread.

A coroutine is a suspendable computation that can pause and resume, letting independently structured tasks share execution cooperatively without running in parallel. Unlike a regular function, it does not need to run from start to finish before another task proceeds. section 2.0 section 2.2

Core mechanics:

  • Calling a coroutine can return a controllable generator object instead of executing the body immediately. section 2.2
  • Each yield pauses execution and preserves the coroutine's state; a later next() resumes from that point. section 2.2
  • Coroutines run within a single thread, providing concurrency without parallelism or additional threads. section 2.1.2 section 2.5

A resumable generator

A coroutine yielding "foo" and then "bar" returns the first value on the first next(coro) call, pauses, and returns the second on the next call. After the final yield, execution reaches return "end" and signals completion through StopIteration, whose value contains "end". section 2.2

def coroutine():
  yield "foo"
  yield "bar"
  return "end"
coro = coroutine()
while True:
  try:
    print(next(coro)) # "foo" then "bar"
  except StopIteration as e:
    print(e.value) # "end"
    break

Use the listing to trace initialization, successive resumptions, yielded values, and final completion. section 2.2

How The Coder Cafe covers it

How deep it goes
Explains generators, yield suspension, saved state, next() resumption, and StopIteration completion, without covering scheduler implementation.
Examples
Demonstrates a generator yielding "foo" and "bar", resuming with next(), and returning "end" through StopIteration.
What it assumes
Assumes familiarity with functions and subroutines, then contrasts their call-and-return behavior with resumable execution.
What you can do after
Apply it via yield, next(), and StopIteration to structure cooperative, non-blocking tasks within one thread.
How it connects
Connects coroutines to concurrency, parallelism, asynchronous I/O, generators, and single-threaded execution.

Also explained in

Compare how 9 books explain coroutine →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Coder Cafe. The section links point to the parts of the book it draws on.