|20-CS-4003-001||Organization of Programming Languages||Fall 2017|
Classic uses of coroutines are to support data driven computation
and operating system services. Coroutines are provided for in Scheme by
call-with-current-continuation. Instead of multiple process
threads, and therefore stacks, Scheme features a heap structure which
is a tree with nodes representing state and a procedure holding that
state, edges representing state transitions due to procedure calls,
leaves representing currently running procedures and their state, and
a single root representing the start state and a top level program.
As nested procedure calls are made, a chain of nodes on a path from
the root gets longer, as does a system stack. If a continuation is
"grabbed" a reference to that node in the heap is saved. In further
computation, procedures may finish and return values. In the heap,
that corresponds to removing current leaf nodes from the heap.
However, a leaf node for which there is a saved continuation reference
is not removed, nor are any of the nodes below it. Then, if the chain
needs to grow again, a separate chain is started from the node
representing the current state. A continuation grabbed on that chain
will cause more chains and so on. At any time, one of those saved
contination references may be invoked and control jumps to the node in
the heap that it references with a user-supplied value that replaces
the value the procedure that had been invoked would have originally
returned. With multiple continuations referenced, control can be
passed back and forth between the two nodes which are on different
chains. The effect is that the running procedures represented by
those nodes are coroutines. The great thing about this is that
execution is completely predictable.
The link to the left opens a trail that explains call-with-current-continuation.
|Java||-||Java provides threads for coroutining. Although more can be done with threads than with continuations, for example exploiting multiprocessor architectures, care has to be taken to ensure proper synchronization when required. In contrast to Scheme heaps, threads provide independent, separate system stacks. The link to the left follows a trail that explains threads in Java.|