In computer science, coroutines are program components that generalize subroutines to allow multiple entry points and suspending and resuming of execution at certain locations. Coroutines are more generic and flexible than subroutines, but are less widely used in practice. Coroutines originated as an assembly-language technique, but are supported in some high-level languages, Simula and Modula-2 being two early examples. Coroutines are well-suited for implementing more familiar program components such as cooperative tasks, iterators, infinite lists, and pipes.
When calling a subroutine, control passes to the top of the subroutine. At the end of every subroutine (and optionally in the middle as well) is a return command, which returns control to the caller.
When calling into a a set of coroutines, control passes to the top of the first coroutine or the specified coroutine. Somewhere within at least one of the coroutines is a return command, which returns control to the caller. Every coroutine must end with either a yield command or a return command.
The yield command is used only between coroutines. It resembles both the call command and the return command, but it is different from both.
The executing coroutine can, at any time, explicitly yield control to any other coroutine. When yielding to another coroutine, control passes to the other coroutine wherever it left off. (If the other coroutine has not executed previously, then it begins execution from the top.) Control might return to the coroutine that yielded, but it might not. If control ever does return, it is not definite from which other coroutine control will be returned. (Assuming there are more than two coroutines in the set.)
The yield command resembles the call command because the coroutine executing it gives up control and might get it back. The yield command resembles the return command, because the coroutine that is yielded to merely resumes executing. Yield is like a return command that does not use the stack, but instead resumes executing the specified named procedure. (Any number of coroutines might be suspended.)
Each coroutine can be re-entered any number times. Each yield is not tracked at all, as there is no reverse of yield. The overhead for coroutines is minimal. There is no context switching at all. Only the addition of an IP (Instruction Pointer) for each coroutine is required to track the re-entry point. The Yield command simply saves the IP of the next instruction in the current coroutine and then jumps to the IP stored for the target coroutine. Also, the entry point for the set of coroutines must reset all of the IPs before execution can begin.
var q := new queue coroutine produce loop while q is not full create some new items add the items to q yield to consume coroutine consume loop while q is not empty remove some items from q use the items yield to produce
Each coroutine does as much work as it can before yielding control to the other using the yield command. The yield causes control in the other coroutine to pick up where it left off, but now with the queue modified so that it can do more work. Although this example is often used to introduce multithreading, it's not necessary to have two threads to effect this dynamic: the yield statement can be implemented by a branch directly from one routine into the other.
The real power of coroutines becomes evident in more complicated examples. If the first coroutine has TWO yield commands, then when control is yielded back to it, it has to continue from the right place. In that case, the functioning of the yield command can no longer be reduced to a simple jump command.
Each time a subroutine is called (invoked), execution starts at the beginning of the invoked subroutine. The first time a coroutine is invoked, execution starts at the beginning of the coroutine. However, each time a coroutine is resumed (by use of the yield command), execution resumes following the place where the coroutine last (yielded from).
A set of coroutines can accept arguments and return values, just as a subroutine.
A coroutine can be useful to generate a series of numbers
Since a subroutine returns only once, returning multiple values requires returning a collection of values. (Some languages, like Forth and Perl allow convenient returning of collections, while other languages like C only permit a single return value, which then needs to be a reference to a collection of values.) In contrast, since coroutines can yield multiple times, passing multiple values merely requires returning additional values upon subsequent calls to the coroutine. (This is a trivial use of coroutines, which could be replaced by inline code.) Routines in which subsequent calls yield additional results are often known as generators.
Subroutines only require a single stack that can be preallocated at the beginning of program execution. In contrast, coroutines, able to call on other coroutines as peers, are best implemented using continuations. Continuations may require allocation of additional stacks and therefore are more commonly implemented in garbage-collected high-level languages. Coroutine creation can be done cheaply by preallocating stacks or caching previously allocated stacks.
Called coroutine:
A coroutine is called and it returns just like a subroutine, except that it preserves its internal execution state between calls. A subroutine has one entry point and can use any number of exit points (return statements). When a subroutine is called again, it begins execution at the top. A coroutine has one "initial" entry point and can use any number of return statements. When a coroutine is called "for the first time", it begins execution at the top. When a coroutine is called again, it resumes execution at the point immediately after the return statement that concluded the last call. The coroutine preserves its internal execution state between calls. That lets it do some interesting things. For example, code like "return 5; return 7; return 9;" actually means something, and it is much simpler code than a state-machine subroutine that could do the same thing. (Since there is a "first time" provision, there could be a special action to re-initialize the coroutine. In object-oriented scenarios, there would be ways to discard an instance of a coroutine and create a new instance.) (Multiple explicit entry points could allow the calling statement could specify where the coroutine should begin or resume executing. But multiple entry can also apply to subroutines, and is a different topic.) (Arguments passed to a called coroutine could update the formal parameters every time the coroutine is called.) A called coroutine can return a sequence of values by returning a different value each time it is called. C# includes a new keyword, "yield return" that can be used within a declared IEnumerator that allows it to continue executing the next time it is called. *
Peer coroutines:
A coroutine can yield control to a specified peer coroutine. When a coroutine receives control "for the first time", it begins execution at the top. When a coroutine receives control again, it resumes execution at the point immediately after the Yield statement that released control the last time. Each peer coroutine preserves its internal execution state while it is inactive.
Puzzles arise when trying to combine a called coroutine with peer coroutines. If the called coroutine yields to a peer coroutine, the peer coroutine could return a value. On the next call, where will execution continue? This can be resolved by grouping the peer coroutines as a set, or by not allowing returns from the peer coroutine, only the one that was called.
Since continuations can be used to implement coroutines, programming languages that support them can also quite easily support coroutines.
In situations in which a coroutine would be the natural implementation of a mechanism, but is not available, the typical response is to create a subroutine that uses an ad-hoc assemblage of boolean flags and other state variables to maintain an internal state between calls. Conditionals within the code result in the execution of different code paths on successive calls, based on the values of the state variables. Another typical response is to implement an explicit state machine in the form of a large and complex switch statement. Such implementations are difficult to understand and maintain.
Threads are an alternative to coroutines in mainstream programming environments today. Threads provide facilities for managing the realtime cooperative interaction of "simultaneously" executing pieces of code. Because they solve a large and difficult problem, they include many powerful and complex facilities and have a concomitantly difficult learning curve. When a coroutine is all that is needed, using a thread can be overkill. However—unlike other alternatives—threads are widely available in environments that support C, are familiar to many programmers, and are usually well-implemented, well-documented and well-supported. A standard and well-defined thread implementation is available within POSIX under the name pthread.
One important difference between threads and coroutines is that threads are typically preemptively scheduled while coroutines are not. Because threads can be rescheduled at any instant and can execute concurrently, programs using threads must be careful about locking. In contrast, because coroutines can only be rescheduled at specific points in the program and do not execute concurrently, programs using coroutines can often avoid locking entirely. (This property is also cited as a benefit of event-driven or asynchronous programming.)
Threads can explicitly release the processor by "sleeping". Threads can reactivate sleeping threads by waking them up. The wake-up is not immediate, it depends on the scheduler. Coroutines can hand off control instantly.
Several attempts have been made, with varying degrees of success, to implement coroutines in C with combinations of subroutines and macros. Simon Tatham's contribution (see below) is a good example of the genre, and his own comments provide a good evaluation of the limitations of this approach. The use of such a device truly can improve the writability, readability and maintainability of a piece of code, but is likely to prove controversial. In Tatham's words: "Of course, this trick violates every coding standard in the book... * any coding standard which insists on syntactic clarity at the expense of algorithmic clarity should be rewritten. If your employer fires you for using this trick, tell them that repeatedly as the security staff drag you out of the building."
A more reliable approach to implementing coroutines in C is to give up on absolute portability and write processor-family-specific implementations, in assembly, of functions to save and restore a coroutine context. A third function, which can usually be written in machine-specific C, is needed to create the context for a new coroutine. Some C libraries provide such routines under the names getcontext, setcontext, makecontext and swapcontext. Russ Cox's libtask library (see below) is a good example of this genre. It uses the context functions if they are provided by the native C library; otherwise it provides its own implementations for ARM, PowerPC, Sparc, and x86. The main shortcoming of this approach is that the coroutine's stack is a fixed size and cannot be grown during execution. Thus, programs tend to allocate much more stack than they actually need in order to avoid the potential for stack overflow.
Notable implementations:
コルーチン | Сопрограмма | 协程
This article is licensed under the GNU Free Documentation License.
It uses material from the
"Coroutine".
Home Page • arts • business • computers • games • health • hospitals • home • kids & teens • news • physicians • recreation• reference • regional • science • shopping • society • sports • world