Coroutine
Encyclopedia : C : CO : COR : Coroutine
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.
- 1 Comparison of coroutines and subroutines
- 2 Example of coroutines
- 3 Detailed comparison
- 4 Called and peer coroutines
- 5 Common uses of coroutines
- 6 Programming languages supporting coroutines
- 7 Coroutine alternatives and implementations
- 7.1 Implementations for
- 7.2 Implementations for
- 7.3 Implementations for
- 7.4 Implementations for
- 7.5 Implementations for functional languages
- 8 References
- 9 See also
Comparison of coroutines and subroutines
The main program can call a subroutine or it can call into a set of peer coroutines. (Coroutines are thought of as sets because each peer coroutine names one or more of its peers.)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.
Example of coroutines
Here's a simple example of how coroutines can be useful. Suppose you have a consumer-producer relationship where one routine creates items and adds them to a queue and another removes items from the queue and uses them. For reasons of efficiency, you want to add and remove several items at once. The code might look like this:
var q := new queueEach 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.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
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.
Detailed comparison
Since coroutines can have more points of entry than subroutines, it is possible to implement any subroutine as a lone coroutine. "Subroutines are special cases of ... coroutines." —Donald KnuthEach 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 and peer coroutines
Two distinct kinds of functionality are implied by the term "coroutine". It is not always clear which functionality is being discussed or utilized. What they have in common is, the coroutine preserves its internal state of execution, not just its static variables. A coroutine resembles a spearate executing program.
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. [link]
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.
Common uses of coroutines
Coroutines are useful to implement the following:- State machines within a single subroutine, where the state is determined by the current entry/exit point of the procedure; this can result in more readable code.
- Actor model of concurrency, for instance in computer games. Each actor has its own procedures (this again logically separates the code), but they voluntarily give up control to central scheduler, which executes them sequentially (this is a form of cooperative multitasking).
- Generators, and these are useful for input/output and for generic traversal of data structures.
Programming languages supporting coroutines
Since continuations can be used to implement coroutines, programming languages that support them can also quite easily support coroutines.Coroutine alternatives and implementations
As of 2003, many of the most popular programming languages, including C and its derivatives, do not have direct support for coroutines within the language or their standard libraries. (This is, in large part, due to the limitations of stack-based subroutine implementation).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.
Implementations for The standard C library includes functions named setjmp and longjmp which can be used to implement a form of coroutine. Unfortunately, as Harbison and Steele note, "the setjmp and longjmp functions are notoriously difficult to implement, and the programmer would do well to make minimal assumptions about them." What this means is if Harbison and Steele's many cautions and caveats are not carefully heeded, uses of setjmp and longjmp that appear to work in one environment may not work in another. Worse yet, faulty implementations of these routines are not rare. The setcontext family of functions are considerably more powerful than setjmp/longjmp, but conforming implementations are as rare if not rarer.
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... [but] 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:
- [link] - Simon Tatham's implementation of coroutines in C.
- [Portable Coroutine Library] - C library using POSIX/SUSv3 facilities.
- [link] - Edgar Toernig's coro library for x86, Linux & FreeBSD.
- [link] - Russ Cox's libtask coroutine library for FreeBSD, Linux, OS X, and SunOS.
- [link] - libCoroutine for FreeBSD, Linux, OS X PPC and x86, SunOS, Symbian and others.
Implementations for
Implementations for
Implementations for
- [Coro]
Implementations for functional languages
Most functional languages implement coroutines, most notably Scheme, Lisp and Haskell.
Implementations for
- [Coro]
Implementations for functional languages
Most functional languages implement coroutines, most notably Scheme, Lisp and Haskell.
References
- Donald Knuth. Fundamental Algorithms, Third Edition. Addison-Wesley, 1997. ISBN 0-201-89683-4. Section 1.4.2: Coroutines, pp.193–200.
- C: A Reference Manual. Samuel P. Harbison and Guy L. Steele, Jr. Third edition; Prentice-Hall, 1991, ISBN 0-13-110933-2.
See also
From Wikipedia, the Free Encyclopedia. Original article here. Support Wikipedia by contributing or donating.
All text is available under the terms of the GNU Free Documentation License See Wikipedia Copyrights for details.
