Another weekend, another weekend read, this time all about Coroutines
I am writing a book on Thinking in Distributed Systems. 12 chapters, one chapter per month, full of diagrams, illustrations, and examples, all about distributed systems.
In their paper Revisiting Coroutines, Ana Lucia de Moura & Roberto Ierusalimschy present a formal yet accessible examination of coroutines.
Coroutines were introduced in the early 1960s and constitute one of the oldest proposals of a general control abstraction. The fundamental characteristics of coroutines are:
the values of data local to a coroutine persist between successive calls
the execution of a coroutine is suspended as control leaves it, only to carry on where it left off when control re-enters the coroutine at some later stage
The authors present the most accurate yet concise description of coroutines I have encountered so far:
Small step operational semantics—“the math”—may be intimidating at first, but communicates a crystal clear mental model:
(4) create takes a function (v) and returns a reference (l); internally, the function is associated with the reference.
(5) resume takes a reference (l) and a value (v), looks up the function associated with the reference and invokes the function with the value (O(l) v).
(6) yield creates an anonymous function that represents the continuation of this coroutine; internally, the function is associated with the reference.
(7) When the coroutine terminates, return its return value (v).
A challenging yet enlightening Weekend Read
Happy Reading
Revisiting Coroutines
Ana Lucia de Moura & Roberto Ierusalimschy
This paper defends the revival of coroutines as a general control abstraction. After proposing a new classification of coroutines, we introduce the concept of full asymmetric coroutines and provide a precise definition for it through an operational semantics. We then demonstrate that full coroutines have an expressive power equivalent to one-shot continuations and one-shot partial continuations. We also show that full asymmetric coroutines and one-shot partial continuations have many similarities, and therefore present comparable benefits. Nevertheless, coroutines are easier implemented and understood, specially in the realm of procedural languages. Finally, we provide a collection of programming examples that illustrate the use of full asymmetric coroutines to support direct and concise implementations of several useful control behaviors, including cooperative multitasking.