Coroutines
   HOME

TheInfoList



OR:

Coroutines are
computer program A computer program is a sequence or set of instructions in a programming language for a computer to execute. Computer programs are one component of software, which also includes documentation and other intangible components. A computer program ...
components that generalize
subroutine In computer programming, a function or subroutine is a sequence of program instructions that performs a specific task, packaged as a unit. This unit can then be used in programs wherever that particular task should be performed. Functions may ...
s for non-preemptive multitasking, by allowing execution to be suspended and resumed. Coroutines are well-suited for implementing familiar program components such as cooperative tasks, exceptions,
event loop In computer science, the event loop is a programming construct or design pattern that waits for and dispatches events or messages in a program. The event loop works by making a request to some internal or external "event provider" (that generally ...
s,
iterator In computer programming, an iterator is an object that enables a programmer to traverse a container, particularly lists. Various types of iterators are often provided via a container's interface. Though the interface and semantics of a given iterat ...
s,
infinite list In programming language theory, lazy evaluation, or call-by-need, is an evaluation strategy which delays the evaluation of an expression until its value is needed ( non-strict evaluation) and which also avoids repeated evaluations (sharing). The ...
s and
pipe Pipe(s), PIPE(S) or piping may refer to: Objects * Pipe (fluid conveyance), a hollow cylinder following certain dimension rules ** Piping, the use of pipes in industry * Smoking pipe ** Tobacco pipe * Half-pipe and quarter pipe, semi-circula ...
s.
Melvin Conway Melvin Edward Conway is an American computer scientist, computer programmer, and hacker who coined what is now known as Conway's law: "Organizations, who design systems, are constrained to produce designs which are copies of the communication stru ...
coined the term ''coroutine'' in 1958 when he applied it to the construction of an assembly program. The first published explanation of the coroutine appeared later, in 1963.


Comparison with


Subroutines

Subroutines are special cases of coroutines. When subroutines are invoked, execution begins at the start, and once a subroutine exits, it is finished; an instance of a subroutine only returns once, and does not hold state between invocations. By contrast, coroutines can exit by calling other coroutines, which may later return to the point where they were invoked in the original coroutine; from the coroutine's point of view, it is not exiting but calling another coroutine. Thus, a coroutine instance holds state, and varies between invocations; there can be multiple instances of a given coroutine at once. The difference between calling another coroutine by means of "yielding" to it and simply calling another routine (which then, also, would return to the original point), is that the relationship between two coroutines which yield to each other is not that of caller-callee, but instead symmetric. Any subroutine can be translated to a coroutine which does not call ''yield''. Here is 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 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 call produce The queue is then completely filled or emptied before yielding control to the other coroutine using the ''yield'' command. The further coroutines calls are starting right after the ''yield'', in the outer coroutine loop. Although this example is often used as an introduction to multithreading, two threads are not needed for this: the ''yield'' statement can be implemented by a jump directly from one routine into the other.


Threads

Coroutines are very similar to threads. However, coroutines are
cooperatively Cooperation (written as co-operation in British English) is the process of groups of organisms working or acting together for common, mutual, or some underlying benefit, as opposed to working in competition for selfish benefit. Many animal a ...
multitasked, whereas threads are typically preemptively multitasked. Coroutines provide concurrency, because they allow tasks to be performed out of order or in a changeable order, without changing the overall outcome, but they do not provide parallelism, because they do not execute multiple tasks simultaneously. The advantages of coroutines over threads are that they may be used in a hard-realtime context ( switching between coroutines need not involve any
system calls In computing, a system call (commonly abbreviated to syscall) is the programmatic way in which a computer program requests a service from the operating system on which it is executed. This may include hardware-related services (for example, acc ...
or any blocking calls whatsoever), there is no need for synchronization primitives such as
mutex In computer science, a lock or mutex (from mutual exclusion) is a synchronization primitive: a mechanism that enforces limits on access to a resource when there are many threads of execution. A lock is designed to enforce a mutual exclusion concu ...
es, semaphores, etc. in order to guard
critical sections In concurrent programming, concurrent accesses to shared resources can lead to unexpected or erroneous behavior, so parts of the program where the shared resource is accessed need to be protected in ways that avoid the concurrent access. One way to ...
, and there is no need for support from the operating system. It is possible to implement coroutines using preemptively-scheduled threads, in a way that will be transparent to the calling code, but some of the advantages (particularly the suitability for hard-realtime operation and relative cheapness of switching between them) will be lost.


Generators

Generators, also known as semicoroutines, are a subset of coroutines. Specifically, while both can yield multiple times, suspending their execution and allowing re-entry at multiple entry points, they differ in coroutines' ability to control where execution continues immediately after they yield, while generators cannot, instead transferring control back to the generator's caller. That is, since generators are primarily used to simplify the writing of
iterator In computer programming, an iterator is an object that enables a programmer to traverse a container, particularly lists. Various types of iterators are often provided via a container's interface. Though the interface and semantics of a given iterat ...
s, the yield statement in a generator does not specify a coroutine to jump to, but rather passes a value back to a parent routine. However, it is still possible to implement coroutines on top of a generator facility, with the aid of a top-level dispatcher routine (a
trampoline A trampoline is a device consisting of a piece of taut, strong fabric stretched between a steel frame using many coiled spring (device), springs. Not all trampolines have springs, as the Springfree Trampoline uses glass-reinforced plastic rods. ...
, essentially) that passes control explicitly to child generators identified by tokens passed back from the generators: ''var'' q := new queue generator produce loop while q is not full create some new items add the items to q yield consume generator consume loop while q is not empty remove some items from q use the items yield produce subroutine dispatcher ''var'' d := new dictionary(generator → iterator) d roduce:= start produce d onsume:= start consume ''var'' current := produce loop call current current := next d urrent call dispatcher A number of implementations of coroutines for languages with generator support but no native coroutines (e.g. Python before 2.5) use this or a similar model.


Mutual recursion

Using coroutines for state machines or concurrency is similar to using
mutual recursion In mathematics and computer science, mutual recursion is a form of recursion where two mathematical or computational objects, such as functions or datatypes, are defined in terms of each other. Mutual recursion is very common in functional progra ...
with
tail call In computer science, a tail call is a subroutine call performed as the final action of a procedure. If the target of a tail is the same subroutine, the subroutine is said to be tail recursive, which is a special case of direct recursion. Tail recur ...
s, as in both cases the control changes to a different one of a set of routines. However, coroutines are more flexible and generally more efficient. Since coroutines yield rather than return, and then resume execution rather than restarting from the beginning, they are able to hold state, both variables (as in a closure) and execution point, and yields are not limited to being in tail position; mutually recursive subroutines must either use shared variables or pass state as parameters. Further, each mutually recursive call of a subroutine requires a new stack frame (unless
tail call elimination In computer science, a tail call is a subroutine call performed as the final action of a procedure. If the target of a tail is the same subroutine, the subroutine is said to be tail recursive, which is a special case of direct recursion (computer s ...
is implemented), while passing control between coroutines uses the existing contexts and can be implemented simply by a jump.


Common uses

Coroutines are useful to implement the following: *
State machine A finite-state machine (FSM) or finite-state automaton (FSA, plural: ''automata''), finite automaton, or simply a state machine, is a mathematical model of computation. It is an abstract machine that can be in exactly one of a finite number o ...
s 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 compared to use of
goto GoTo (goto, GOTO, GO TO or other case combinations, depending on the programming language) is a statement found in many computer programming languages. It performs a one-way transfer of control to another line of code; in contrast a function ca ...
, and may also be implemented via
mutual recursion In mathematics and computer science, mutual recursion is a form of recursion where two mathematical or computational objects, such as functions or datatypes, are defined in terms of each other. Mutual recursion is very common in functional progra ...
with
tail call In computer science, a tail call is a subroutine call performed as the final action of a procedure. If the target of a tail is the same subroutine, the subroutine is said to be tail recursive, which is a special case of direct recursion. Tail recur ...
s. *
Actor model The actor model in computer science is a mathematical model of concurrent computation that treats ''actor'' as the universal primitive of concurrent computation. In response to a message it receives, an actor can: make local decisions, create more ...
of concurrency, for instance in
video game Video games, also known as computer games, are electronic games that involves interaction with a user interface or input device such as a joystick, controller, keyboard, or motion sensing device to generate visual feedback. This fee ...
s. 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 Cooperative multitasking, also known as non-preemptive multitasking, is a style of computer multitasking in which the operating system never initiates a context switch from a running process to another process. Instead, in order to run multiple ...
). *
Generator Generator may refer to: * Signal generator, electronic devices that generate repeating or non-repeating electronic signals * Electric generator, a device that converts mechanical energy to electrical energy. * Generator (circuit theory), an eleme ...
s, and these are useful for
streams A stream is a continuous body of water, body of surface water Current (stream), flowing within the stream bed, bed and bank (geography), banks of a channel (geography), channel. Depending on its location or certain characteristics, a stream ...
particularly input/outputand for generic traversal of data structures. *
Communicating sequential processes In computer science, communicating sequential processes (CSP) is a formal language for describing patterns of interaction in concurrent systems. It is a member of the family of mathematical theories of concurrency known as process algebras, or pro ...
where each sub-process is a coroutine. Channel inputs/outputs and blocking operations yield coroutines and a scheduler unblocks them on completion events. Alternatively, each sub-process may be the parent of the one following it in the data pipeline (or preceding it, in which case the pattern can be expressed as nested generators). * Reverse communication, commonly used in mathematical software, wherein a procedure such as a solver, integral evaluator, ... needs the using process to make a computation, such as evaluating an equation or integrand.


Native support

Coroutines originated as an
assembly language In computer programming, assembly language (or assembler language, or symbolic machine code), often referred to simply as Assembly and commonly abbreviated as ASM or asm, is any low-level programming language with a very strong correspondence be ...
method, but are supported in some
high-level programming language In computer science, a high-level programming language is a programming language with strong Abstraction (computer science), abstraction from the details of the computer. In contrast to low-level programming languages, it may use natural language ...
s. *
Aikido Aikido ( , , , ) is a modern Japanese martial art that is split into many different styles, including Iwama Ryu, Iwama Shin Shin Aiki Shuren Kai, Shodokan Aikido, Yoshinkan, Renshinkai, Aikikai and Ki Aikido. Aikido is now practiced in around 1 ...
*
AngelScript AngelScript is a game-oriented compiled scripting language. AngelScript features static typing, object handles (similar to C++ pointers but garbage collected via reference counting), object-orientation, single inheritance, multiple inheritance ...
*
Ballerina A ballet dancer ( it, ballerina fem.; ''ballerino'' masc.) is a person who practices the art of classical ballet. Both females and males can practice ballet; however, dancers have a strict hierarchy and strict gender roles. They rely on yea ...
*
BCPL BCPL ("Basic Combined Programming Language") is a procedural, imperative, and structured programming language. Originally intended for writing compilers for other languages, BCPL is no longer in common use. However, its influence is still ...
*
Pascal Pascal, Pascal's or PASCAL may refer to: People and fictional characters * Pascal (given name), including a list of people with the name * Pascal (surname), including a list of people and fictional characters with the name ** Blaise Pascal, Fren ...
(Borland
Turbo Pascal Turbo Pascal is a software development system that includes a compiler and an integrated development environment (IDE) for the Pascal (programming language), Pascal programming language running on CP/M, CP/M-86, and DOS. It was originally develo ...
7.0 with uThreads module) *
BETA Beta (, ; uppercase , lowercase , or cursive ; grc, βῆτα, bē̂ta or ell, βήτα, víta) is the second letter of the Greek alphabet. In the system of Greek numerals, it has a value of 2. In Modern Greek, it represents the voiced labiod ...
*
BLISS BLISS is a system programming language developed at Carnegie Mellon University (CMU) by W. A. Wulf, D. B. Russell, and A. N. Habermann around 1970. It was perhaps the best known system language until C debuted a few years later. Since then, C b ...
*
C++ C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
(Since C++20) * C# (Since 2.0) *
Chapel A chapel is a Christian place of prayer and worship that is usually relatively small. The term has several meanings. Firstly, smaller spaces inside a church that have their own altar are often called chapels; the Lady chapel is a common ty ...
*
ChucK Chuck is a masculine given name or a nickname for Charles or Charlie. It may refer to: People Arts and entertainment * Chuck Alaimo, American saxophonist, leader of the Chuck Alaimo Quartet * Chuck Barris (1929–2017), American TV producer * C ...
* CLU * D *
Dynamic C Dynamics (from Greek δυναμικός ''dynamikos'' "powerful", from δύναμις ''dynamis'' "power") or dynamic may refer to: Physics and engineering * Dynamics (mechanics) ** Aerodynamics, the study of the motion of air ** Analytical dynam ...
* Erlang * F# *
Factor Factor, a Latin word meaning "who/which acts", may refer to: Commerce * Factor (agent), a person who acts for, notably a mercantile and colonial agent * Factor (Scotland), a person or firm managing a Scottish estate * Factors of production, suc ...
*
GameMonkey Script {{Portal, Free and open-source software GameMonkey Script is a small, cross-platform scripting language designed for embedding into games. GameMonkey bears many similarities to Lua, except the syntax is more similar to that of C. History Game ...
*
GDScript Godot ( /ˈɡɒdoʊ/) is a cross-platform, free and open-source game engine released under the MIT license. It was initially developed by Argentine software developers Juan Linietsky and Ariel Manzur for several companies in Latin America prior ...
(Godot's scripting language) * Go *
Haskell Haskell () is a general-purpose, statically-typed, purely functional programming language with type inference and lazy evaluation. Designed for teaching, research and industrial applications, Haskell has pioneered a number of programming lan ...
*
High Level Assembly High Level Assembly (HLA) is a language developed by Randall Hyde that allows the use of higher-level language constructs to aid both beginners and advanced assembly developers. It fully supports advanced data types and object-oriented programmi ...
*
Icon An icon () is a religious work of art, most commonly a painting, in the cultures of the Eastern Orthodox, Oriental Orthodox, and Catholic churches. They are not simply artworks; "an icon is a sacred image used in religious devotion". The most ...
* Io *
JavaScript JavaScript (), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of Website, websites use JavaScript on the Client (computing), client side ...
(since 1.7, standardized in ECMAScript 6) ECMAScript 2017 also includes
await In computer programming, the async/await pattern is a syntactic feature of many programming languages that allows an Asynchrony (computer programming), asynchronous, non-blocking I/O, non-blocking Subroutine, function to be structured in a way simi ...
support. *
Julia Julia is usually a feminine given name. It is a Latinate feminine form of the name Julio and Julius. (For further details on etymology, see the Wiktionary entry "Julius".) The given name ''Julia'' had been in use throughout Late Antiquity (e.g. ...
* Kotlin (since 1.1) *
Limbo In Catholic theology, Limbo (Latin '' limbus'', edge or boundary, referring to the edge of Hell) is the afterlife condition of those who die in original sin without being assigned to the Hell of the Damned. Medieval theologians of Western Euro ...
*
Lua Lua or LUA may refer to: Science and technology * Lua (programming language) * Latvia University of Agriculture * Last universal ancestor, in evolution Ethnicity and language * Lua people, of Laos * Lawa people, of Thailand sometimes referred t ...
*
Lucid LUCID (Langton Ultimate Cosmic ray Intensity Detector) is a cosmic ray detector built by Surrey Satellite Technology Ltd and designed at Simon Langton Grammar School for Boys, in Canterbury, England. Its main purpose is to monitor cosmic rays usi ...
* µC++ *
Modula-2 Modula-2 is a structured, procedural programming language developed between 1977 and 1985/8 by Niklaus Wirth at ETH Zurich. It was created as the language for the operating system and application software of the Lilith personal workstation. It w ...
*
Nemerle Nemerle is a general-purpose, high-level, statically typed programming language designed for platforms using the Common Language Infrastructure ( .NET/Mono). It offers functional, object-oriented, aspect-oriented, reflective and imperative fea ...
*
Perl 5 Perl is a family of two High-level programming language, high-level, General-purpose programming language, general-purpose, Interpreter (computing), interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it ...
(using th
Coro module
*
PHP PHP is a general-purpose scripting language geared toward web development. It was originally created by Danish-Canadian programmer Rasmus Lerdorf in 1993 and released in 1995. The PHP reference implementation is now produced by The PHP Group ...
(wit
HipHop
native since PHP 5.5) *
Picolisp PicoLisp is a programming language, a dialect of the language Lisp. It runs on operating systems including Linux and others that are ''Portable Operating System Interface'' (POSIX) compliant. Its most prominent features are simplicity and minimali ...
*
Prolog Prolog is a logic programming language associated with artificial intelligence and computational linguistics. Prolog has its roots in first-order logic, a formal logic, and unlike many other programming languages, Prolog is intended primarily ...
*
Python Python may refer to: Snakes * Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia ** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia * Python (mythology), a mythical serpent Computing * Python (pro ...
(since 2.5, with improved support since 3.3 and with explicit syntax since 3.5) * Raku *
Ruby A ruby is a pinkish red to blood-red colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sa ...
*
Rust Rust is an iron oxide, a usually reddish-brown oxide formed by the reaction of iron and oxygen in the catalytic presence of water or air moisture. Rust consists of hydrous iron(III) oxides (Fe2O3·nH2O) and iron(III) oxide-hydroxide (FeO(OH ...
(since 1.39) *
Sather Sather is an object-oriented programming language. It originated circa 1990 at the International Computer Science Institute (ICSI) at the University of California, Berkeley, developed by an international team led by Steve Omohundro. It supports ...
*
Scheme A scheme is a systematic plan for the implementation of a certain idea. Scheme or schemer may refer to: Arts and entertainment * ''The Scheme'' (TV series), a BBC Scotland documentary series * The Scheme (band), an English pop band * ''The Schem ...
*
Self The self is an individual as the object of that individual’s own reflective consciousness. Since the ''self'' is a reference by a subject to the same subject, this reference is necessarily subjective. The sense of having a self—or ''selfhood ...
*
Simula Simula is the name of two simulation programming languages, Simula I and Simula 67, developed in the 1960s at the Norwegian Computing Center in Oslo, by Ole-Johan Dahl and Kristen Nygaard. Syntactically, it is an approximate superset of ALGOL 6 ...
67 *
Smalltalk Smalltalk is an object-oriented, dynamically typed reflective programming language. It was designed and created in part for educational use, specifically for constructionist learning, at the Learning Research Group (LRG) of Xerox PARC by Alan Ka ...
*
Squirrel Squirrels are members of the family Sciuridae, a family that includes small or medium-size rodents. The squirrel family includes tree squirrels, ground squirrels (including chipmunks and prairie dogs, among others), and flying squirrels. Squ ...
*
Stackless Python Stackless Python, or Stackless, is a Python programming language interpreter, so named because it avoids depending on the C call stack for its own stack. In practice, Stackless Python uses the C stack, but the stack is cleared between function c ...
* SuperCollider *
Tcl TCL or Tcl or TCLs may refer to: Business * TCL Technology, a Chinese consumer electronics and appliance company **TCL Electronics, a subsidiary of TCL Technology * Texas Collegiate League, a collegiate baseball league * Trade Centre Limited ...
(since 8.6) *
urbiscript urbiscript is a programming language for robotics. It features syntactic support for concurrency and event-based programming. It is a prototype-based object-oriented scripting language. It is dynamic: name resolution is performed during the ...
Since
continuation In computer science, a continuation is an abstract representation of the control state of a computer program. A continuation implements ( reifies) the program control state, i.e. the continuation is a data structure that represents the computati ...
s can be used to implement coroutines, programming languages that support them can also quite easily support coroutines.


Implementations

, 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. An exception is the C++ librar
Boost.Context
part o
boost libraries
which supports context swapping on ARM, MIPS, PowerPC, SPARC and x86 on POSIX, Mac OS X and Windows. Coroutines can be built upon Boost.Context. In situations where a coroutine would be the natural implementation of a mechanism, but is not available, the typical response is to use a closurea subroutine with state variables (
static variable In computer programming, a static variable is a variable that has been allocated "statically", meaning that its lifetime (or "extent") is the entire run of the program. This is in contrast to shorter-lived automatic variables, whose storage is ...
s, often boolean flags) to maintain an internal state between calls, and to transfer control to the correct point. 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 In computer programming languages, a switch statement is a type of selection control mechanism used to allow the value of a variable or expression to change the control flow of program execution via search and map. Switch statements function some ...
or via a
goto GoTo (goto, GOTO, GO TO or other case combinations, depending on the programming language) is a statement found in many computer programming languages. It performs a one-way transfer of control to another line of code; in contrast a function ca ...
statement, particularly a
computed goto GoTo (goto, GOTO, GO TO or other case combinations, depending on the programming language) is a statement found in many computer programming languages. It performs a one-way transfer of control to another line of code; in contrast a function ca ...
. Such implementations are considered difficult to understand and maintain, and a motivation for coroutine support. Threads, and to a lesser extent
fibers Fiber or fibre (from la, fibra, links=no) is a natural or artificial substance that is significantly longer than it is wide. Fibers are often used in the manufacture of other materials. The strongest engineering materials often incorporate ...
, are an alternative to coroutines in mainstream programming environments today. Threads provide facilities for managing the real-time cooperative interaction of ''simultaneously'' executing pieces of code. Threads are widely available in environments that support C (and are supported natively in many other modern languages), are familiar to many programmers, and are usually well-implemented, well-documented and well-supported. However, as they solve a large and difficult problem they include many powerful and complex facilities and have a correspondingly difficult learning curve. As such, when a coroutine is all that is needed, using a thread can be overkill. 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 Event driven may refer to: The term event-driven refers to a methodology that focuses on events and event dependencies. Examples include * Event-driven finite-state machine, finite-state machine where the transition from one state to another ...
or asynchronous programming. Since fibers are cooperatively scheduled, they provide an ideal base for implementing coroutines above.Implementing Coroutines for .NET by Wrapping the Unmanaged Fiber API
, Ajai Shankar,
MSDN Magazine Microsoft Developer Network (MSDN) was the division of Microsoft responsible for managing the firm's relationship with developers and testers, such as hardware developers interested in the operating system (OS), and software developers developing ...
However, system support for fibers is often lacking compared to that for threads.


C

In order to implement general-purpose coroutines, a second
call stack In computer science, a call stack is a stack data structure that stores information about the active subroutines of a computer program. This kind of stack is also known as an execution stack, program stack, control stack, run-time stack, or ma ...
must be obtained, which is a feature not directly supported by the C language. A reliable (albeit platform-specific) way to achieve this is to use a small amount of
inline assembly In computer programming, an inline assembler is a feature of some compilers that allows low-level code written in assembly language to be embedded within a program, among code that otherwise has been compiled from a higher-level language such as C ...
to explicitly manipulate the stack pointer during initial creation of the coroutine. This is the approach recommended by
Tom Duff Tom or TOM may refer to: * Tom (given name), a diminutive of Thomas or Tomás or an independent Aramaic given name (and a list of people with the name) Characters * Tom Anderson, a character in ''Beavis and Butt-Head'' * Tom Beck, a character ...
in a discussion on its relative merits vs. the method used by
Protothreads A protothread is a low-overhead mechanism for concurrent programming. Protothreads function as stackless, lightweight threads, or coroutines, providing a blocking context cheaply using minimal memory per protothread (on the order of single bytes) ...
. On platforms which provide the
POSIX The Portable Operating System Interface (POSIX) is a family of standards specified by the IEEE Computer Society for maintaining compatibility between operating systems. POSIX defines both the system- and user-level application programming interf ...
sigaltstack system call, a second call stack can be obtained by calling a springboard function from within a signal handlerhttps://www.gnu.org/software/pth/rse-pmt.ps to achieve the same goal in portable C, at the cost of some extra complexity. C libraries complying to
POSIX The Portable Operating System Interface (POSIX) is a family of standards specified by the IEEE Computer Society for maintaining compatibility between operating systems. POSIX defines both the system- and user-level application programming interf ...
or the Single Unix Specification (SUSv3) provided such routines as getcontext, setcontext, makecontext and swapcontext, but these functions were declared obsolete in POSIX 1.2008. Once a second call stack has been obtained with one of the methods listed above, the setjmp and longjmp functions in the
standard C library The C standard library or libc is the standard library for the C (programming language), C programming language, as specified in the ISO C standard.International Organization for Standardization, ISO/International Electrotechnical Commission, IEC ...
can then be used to implement the switches between coroutines. These functions save and restore, respectively, the
stack pointer In computer science, a call stack is a stack data structure that stores information about the active subroutines of a computer program. This kind of stack is also known as an execution stack, program stack, control stack, run-time stack, or mach ...
,
program counter The program counter (PC), commonly called the instruction pointer (IP) in Intel x86 and Itanium microprocessors, and sometimes called the instruction address register (IAR), the instruction counter, or just part of the instruction sequencer, is ...
, callee-saved registers, and any other internal state as required by the ABI, such that returning to a coroutine after having yielded restores all the state that would be restored upon returning from a function call. Minimalist implementations, which do not piggyback off the setjmp and longjmp functions, may achieve the same result via a small block of
inline assembly In computer programming, an inline assembler is a feature of some compilers that allows low-level code written in assembly language to be embedded within a program, among code that otherwise has been compiled from a higher-level language such as C ...
which swaps merely the stack pointer and program counter, and clobbers all other registers. This can be significantly faster, as setjmp and longjmp must conservatively store all registers which may be in use according to the ABI, whereas the clobber method allows the compiler to store (by spilling to the stack) only what it knows is actually in use. Due to the lack of direct language support, many authors have written their own libraries for coroutines which hide the above details. Russ Cox's libtask libraryhttp://swtch.com/libtask/ - Russ Cox's libtask coroutine library for FreeBSD, Linux, Mac OS X, and SunOS 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. Other notable implementations include libpcl, coro, lthread, libCoroutine, libconcurrency, libcoro, ribs2, libdill., libaco, and libco. In addition to the general approach above, several attempts have been made to approximate coroutines in C with combinations of subroutines and macros.
Simon Tatham Simon Tatham (born 3 May 1977) is a British computer programmer. He created and maintains PuTTY, a free software implementation of Secure Shell (SSH) and Telnet for Microsoft Windows and Unix, along with an xterm terminal emulator. He is also ...
's contribution, based on
Duff's device In the C programming language, Duff's device is a way of manually implementing loop unrolling by interleaving two syntactic constructs of C: the - loop and a switch statement. Its discovery is credited to Tom Duff in November 1983, when Duff was ...
, is a notable example of the genre, and is the basis for
Protothread A protothread is a low-overhead mechanism for concurrent programming. Protothreads function as Call stack, stackless, lightweight Thread (computer science), threads, or coroutines, providing a blocking context cheaply using minimal memory per proto ...
s and similar implementations. In addition to Duff's objections, Tatham's own comments provide a frank evaluation of the limitations of this approach: "As far as I know, this is the worst piece of C hackery ever seen in serious production code." The main shortcomings of this approximation are that, in not maintaining a separate stack frame for each coroutine, local variables are not preserved across yields from the function, it is not possible to have multiple entries to the function, and control can only be yielded from the top-level routine.


C++

*
C++20 C++20 is a version of the ISO/IEC 14882 standard for the C++ programming language. C++20 replaced the prior version of the C++ standard, called C++17. The standard was technically finalized by WG21 at the meeting in Prague in February 2020, a ...
introduced standardized coroutines as stackless functions that can be suspended in the middle of execution and resumed at a later point. The suspended state of a coroutine is stored on the heap. Implementation of this standard is ongoing, with the G++ and MSVC compilers currently fully supporting standard coroutines in recent versions.
Boost.Coroutine
- created by Oliver Kowalke, is the official released portable coroutine library o
boost
since version 1.53. The library relies o

and supports ARM, MIPS, PowerPC, SPARC and X86 on POSIX, Mac OS X and Windows.

- also created by Oliver Kowalke, is a modernized portable coroutine library since boost version 1.59. It takes advantage of C++11 features, but removes the support for symmetric coroutines.
Mordor
- In 2010,
Mozy Mozy () was an online backup service for both Windows and macOS users. Linux's support was made available in Q3, 2014. In 2007 Mozy was acquired by EMC, and in 2013 Mozy was included in the EMC Backup Recovery Systems division's product list. O ...
open sourced a C++ library implementing coroutines, with an emphasis on using them to abstract
asynchronous I/O In computer science, asynchronous I/O (also non-sequential I/O) is a form of input/output processing that permits other processing to continue before the transmission has finished. A name used for asynchronous I/O in the Windows API is overlappe ...
into a more familiar sequential model.
CO2
- stackless coroutine based on C++
preprocessor In computer science, a preprocessor (or precompiler) is a program that processes its input data to produce output that is used as input in another program. The output is said to be a preprocessed form of the input data, which is often used by so ...
tricks, providing await/yield emulation.
ScummVM
- The
ScummVM Script Creation Utility for Maniac Mansion Virtual Machine (ScummVM) is a set of game engine recreations. Originally designed to play LucasArts adventure games that use the SCUMM system, it also supports a variety of non-SCUMM games by companies ...
project implements a light-weight version of stackless coroutines based o
Simon Tatham's article

tonbit::coroutine
- C++11 single .h asymmetric coroutine implementation via ucontext / fiber * Coroutines landed in
Clang Clang is a compiler front end for the C, C++, Objective-C, and Objective-C++ programming languages, as well as the OpenMP, OpenCL, RenderScript, CUDA, and HIP frameworks. It acts as a drop-in replacement for the GNU Compiler Collection (GCC), ...
in May 2017, with libc++ implementation ongoing.
elle
by Docker
oatpp-coroutines
- stackless coroutines with scheduling designed for high-concurrency level I/O operations. Used in th
5-million WebSocket connections
experiment by Oat++. Part of th
Oat++
web framework.


C#


MindTouch Dream
- The MindTouch Dream REST framework provides an implementation of coroutines based on the C# 2.0 iterator pattern
Caliburn
- The Caliburn screen patterns framework for WPF uses C# 2.0 iterators to ease UI programming, particularly in asynchronous scenarios.
Power Threading Library
- The Power Threading Library by Jeffrey Richter implements an AsyncEnumerator that provides simplified Asynchronous Programming Model using iterator-based coroutines. *The
Unity Unity may refer to: Buildings * Unity Building, Oregon, Illinois, US; a historic building * Unity Building (Chicago), Illinois, US; a skyscraper * Unity Buildings, Liverpool, UK; two buildings in England * Unity Chapel, Wyoming, Wisconsin, US; a h ...
game engine implements coroutines.
Servelat Pieces
- The Servelat Pieces project by
Yevhen Bobrov Yevhen ( uk, Євге́н, Jevhén ), also spelled Evhen, is a common Ukrainian name, Ukrainian given name. Its Old Church Slavonic form ''Евгении'' came from the Ancient Greek, Greek ''Eugenios'' (masculine form), names derived from the ...
provides transparent asynchrony for Silverlight WCF services and ability to asynchronously call any synchronous method. The implementation is based on Caliburn's Coroutines iterator and C# iterator blocks.

- The .NET 2.0+ Framework now provides semi-coroutine ( generator (computer programming), generator) functionality through the iterator pattern and yield keyword.
StreamThreads
- StreamThreads is an open source light-weight C# co-routine library based on iterator extension methods. It supports error handling and return values. C# 5.0 includes
await In computer programming, the async/await pattern is a syntactic feature of many programming languages that allows an Asynchrony (computer programming), asynchronous, non-blocking I/O, non-blocking Subroutine, function to be structured in a way simi ...
syntax support.


Clojure

Cloroutine
is a third-party library providing support for stackless coroutines in
Clojure Clojure (, like ''closure'') is a dynamic and functional dialect of the Lisp programming language on the Java platform. Like other Lisp dialects, Clojure treats code as data and has a Lisp macro system. The current development process is comm ...
. It's implemented as a macro, statically splitting an arbitrary code block on arbitrary var calls and emitting the coroutine as a stateful function.


D

D implements coroutines as its standard library clas
Fiber
A ''generator'' makes it trivial to expose a fiber function as an ''input range'', making any fiber compatible with existing range algorithms.


Go

Go has a built-in concept of " goroutines", which are lightweight, independent processes managed by the Go runtime. A new goroutine can be started using the "go" keyword. Each goroutine has a variable-size stack which can be expanded as needed. Goroutines generally communicate using Go's built-in channels.


Java

There are several implementations for coroutines in
Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's List ...
. Despite the constraints imposed by Java's abstractions, the JVM does not preclude the possibility. There are four general methods used, but two break bytecode portability among standards-compliant JVMs. * Modified JVMs. It is possible to build a patched JVM to support coroutines more natively. Th
Da Vinci JVM
has had patches created. * Modified bytecode. Coroutine functionality is possible by rewriting regular Java bytecode, either on the fly or at compile time. Toolkits includ
JavaflowJava Coroutines
an
Coroutines
* Platform-specific JNI mechanisms. These use JNI methods implemented in the OS or C libraries to provide the functionality to the JVM. * Thread abstractions. Coroutine libraries which are implemented using threads may be heavyweight, though performance will vary based on the JVM's thread implementation.


JavaScript


node-fibers
*
Fibjs
- fibjs is a JavaScript runtime built on Chrome's V8 JavaScript engine. fibjs uses fibers-switch, sync style, and non-blocking I/O model to build scalable systems. * Sinc
ECMAScript 2015
stackless coroutine functionality through "generators" and yield expressions is provided.


Kotlin

Kotlin
implements coroutines as part of
first-party library


Modula-2

Modula-2 Modula-2 is a structured, procedural programming language developed between 1977 and 1985/8 by Niklaus Wirth at ETH Zurich. It was created as the language for the operating system and application software of the Lilith personal workstation. It w ...
as defined by Wirth implements coroutines as part of the standard SYSTEM library. The procedure NEWPROCESS() fills in a context given a code block and space for a stack as parameters, and the procedure TRANSFER() transfers control to a coroutine given the coroutine's context as its parameter.


Mono

The
Mono Mono may refer to: Common meanings * Infectious mononucleosis, "the kissing disease" * Monaural, monophonic sound reproduction, often shortened to mono * Mono-, a numerical prefix representing anything single Music Performers * Mono (Japanese b ...
Common Language Runtime has support for continuations,http://www.mono-project.com/Continuations Mono Continuations from which coroutines can be built.


.NET Framework

During the development of the
.NET Framework The .NET Framework (pronounced as "''dot net"'') is a proprietary software framework developed by Microsoft that runs primarily on Microsoft Windows. It was the predominant implementation of the Common Language Infrastructure (CLI) until bein ...
2.0, Microsoft extended the design of the
Common Language Runtime The Common Language Runtime (CLR), the virtual machine component of Microsoft .NET Framework, manages the execution of .NET programs. Just-in-time compilation converts the managed code (compiled intermediate language code) into machine instructio ...
(CLR) hosting APIs to handle fiber-based scheduling with an eye towards its use in fiber-mode for SQL server.http://blogs.msdn.com/cbrumme/archive/2004/02/21/77595.aspx , Chris Brumme
cbrumme's WebLog
/ref> Before release, support for the task switching hook ICLRTask::SwitchOut was removed due to time constraints. Consequently, the use of the fiber API to switch tasks is currently not a viable option in the .NET Framework.


Perl


Coro
Coroutines are natively implemented in all Raku backends.


PHP


Fibers
native since PHP 8.1
Amphp

Open SwooleCoroutine
implemented in a way that resembles
Python Python may refer to: Snakes * Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia ** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia * Python (mythology), a mythical serpent Computing * Python (pro ...
functions, and some Go, man
examples
showing there code converted with same number of lines and behavior.


Python

*
Python Python may refer to: Snakes * Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia ** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia * Python (mythology), a mythical serpent Computing * Python (pro ...
2.5 implements better support for coroutine-like functionality, based on extended generators
PEP 342
*
Python Python may refer to: Snakes * Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia ** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia * Python (mythology), a mythical serpent Computing * Python (pro ...
3.3 improves this ability, by supporting delegating to a subgenerator
PEP 380
*
Python Python may refer to: Snakes * Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia ** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia * Python (mythology), a mythical serpent Computing * Python (pro ...
3.4 introduces a comprehensive asynchronous I/O framework as standardized i
PEP 3156
which includes coroutines that leverage subgenerator delegation *
Python Python may refer to: Snakes * Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia ** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia * Python (mythology), a mythical serpent Computing * Python (pro ...
3.5 introduces explicit support for coroutines with async/
await In computer programming, the async/await pattern is a syntactic feature of many programming languages that allows an Asynchrony (computer programming), asynchronous, non-blocking I/O, non-blocking Subroutine, function to be structured in a way simi ...
syntax
PEP 0492
. *Since
Python Python may refer to: Snakes * Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia ** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia * Python (mythology), a mythical serpent Computing * Python (pro ...
3.7, async/await have become reserved keywords.
EventletGreenletgeventstackless python


Ruby

*
Ruby A ruby is a pinkish red to blood-red colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sa ...
1.9 supports coroutines natively which are implemented a
fibers
which are semi-coroutines.
An implementation by Marc De Scheemaecker
*
Ruby A ruby is a pinkish red to blood-red colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sa ...
2.5 and higher supports coroutines natively which are implemented a
fibers

An implementation by Thomas W Branson


Rust

Rust Rust is an iron oxide, a usually reddish-brown oxide formed by the reaction of iron and oxygen in the catalytic presence of water or air moisture. Rust consists of hydrous iron(III) oxides (Fe2O3·nH2O) and iron(III) oxide-hydroxide (FeO(OH ...
supports coroutines since version 1.39 . There are two popular libraries providing asynchronous runtimes
tokio
an
async-std


Scala

Scala Coroutines is a coroutine implementation for Scala. This implementation is a library-level extension that relies on the Scala macro system to statically transform sections of the program into coroutine objects. As such, this implementation does not require modifications in the JVM, so it is fully portable between different JVMs and works with alternative Scala backends, such as Scala.js, which compiles to JavaScript. Scala Coroutines rely on the coroutine macro that transforms a normal block of code into a coroutine definition. Such a coroutine definition can be invoked with the call operation, which instantiates a coroutine frame. A coroutine frame can be resumed with the resume method, which resumes the execution of the coroutine's body, until reaching a yieldval keyword, which suspends the coroutine frame. Scala Coroutines also expose a snapshot method, which effectively duplicates the coroutine.Scala Coroutine Snapshots
/ref> A detailed descriptions of Scala coroutines with snapshots appeared a
ECOOP 2018
along with thei
formal model


Scheme

Since
Scheme A scheme is a systematic plan for the implementation of a certain idea. Scheme or schemer may refer to: Arts and entertainment * ''The Scheme'' (TV series), a BBC Scotland documentary series * The Scheme (band), an English pop band * ''The Schem ...
provides full support for continuations, implementing coroutines is nearly trivial, requiring only that a queue of continuations be maintained.


Smalltalk

Since, in most
Smalltalk Smalltalk is an object-oriented, dynamically typed reflective programming language. It was designed and created in part for educational use, specifically for constructionist learning, at the Learning Research Group (LRG) of Xerox PARC by Alan Ka ...
environments, the execution stack is a first-class citizen, coroutines can be implemented without additional library or VM support.


Swift


SwiftCoroutine
- Swift coroutines library for iOS, macOS and Linux.


Tool Command Language (Tcl)

Since version 8.6, the Tool Command Language supports coroutines in the core language.


Vala

Vala Vala or VALA may refer to: Religion and mythology * Vala (Vedic), a demon or a stone cavern in the Hindu scriptures * Völva, also spelled Vala, a priestess in Norse mythology and Norse paganism Fiction * Vala (Middle-earth), an angelic being in ...
implements native support for coroutines. They are designed to be used with a Gtk Main Loop, but can be used alone if care is taken to ensure that the end callback will never have to be called before doing, at least, one yield.


Assembly languages

Machine-dependent
assembly language In computer programming, assembly language (or assembler language, or symbolic machine code), often referred to simply as Assembly and commonly abbreviated as ASM or asm, is any low-level programming language with a very strong correspondence be ...
s often provide direct methods for coroutine execution. For example, in
MACRO-11 MACRO-11 is an assembly language with macro facilities, designed for PDP-11 minicomputer family from Digital Equipment Corporation (DEC). It is the successor to Program Assembler Loader ( PAL-11R), an earlier version of the PDP-11 assembly languag ...
, the assembly language of the
PDP-11 The PDP-11 is a series of 16-bit minicomputers sold by Digital Equipment Corporation (DEC) from 1970 into the 1990s, one of a set of products in the Programmed Data Processor (PDP) series. In total, around 600,000 PDP-11s of all models were sold, ...
family of minicomputers, the “classic” coroutine switch is effected by the instruction "JSR PC,@(SP)+", which jumps to the address popped from the stack and pushes the current (''i.e'' that of the next) instruction address onto the stack. On
VAX VAX (an acronym for Virtual Address eXtension) is a series of computers featuring a 32-bit instruction set architecture (ISA) and virtual memory that was developed and sold by Digital Equipment Corporation (DEC) in the late 20th century. The V ...
en (in
VAX MACRO VAX MACRO is the computer assembly language implementing the VAX instruction set architecture for the OpenVMS operating system, originally released by Digital Equipment Corporation (DEC) in 1977. The syntax, directives, macro language, and lexica ...
) the comparable instruction is "JSB @(SP)+". Even on a
Motorola 6809 The Motorola 6809 ("''sixty-eight-oh-nine''") is an 8-bit microprocessor with some 16-bit features. It was designed by Motorola's Terry Ritter and Joel Boney and introduced in 1978. Although source compatible with the earlier Motorola 6800, the 6 ...
there is the instruction "JSR S++; note the "++", as 2 bytes (of address) are popped from the stack. This instruction is much used in the (standard) 'monitor'
Assist Assist or ASSIST may refer to: Sports Several sports have a statistic known as an "assist", generally relating to action by a player leading to a score by another player on their team: *Assist (basketball), a pass by a player that facilitates a ba ...
09.


See also

*
Async/await In computer programming, the async/await pattern is a syntactic feature of many programming languages that allows an asynchronous, non-blocking function to be structured in a way similar to an ordinary synchronous function. It is semantically rel ...
*
Pipeline Pipeline may refer to: Electronics, computers and computing * Pipeline (computing), a chain of data-processing stages or a CPU optimization found on ** Instruction pipelining, a technique for implementing instruction-level parallelism within a s ...
, a kind of coroutine used for communicating between programs *
Protothreads A protothread is a low-overhead mechanism for concurrent programming. Protothreads function as stackless, lightweight threads, or coroutines, providing a blocking context cheaply using minimal memory per protothread (on the order of single bytes) ...
, a stackless lightweight thread implementation using a coroutine like mechanism


References


Further reading

*


External links

*
Simon Tatham Simon Tatham (born 3 May 1977) is a British computer programmer. He created and maintains PuTTY, a free software implementation of Secure Shell (SSH) and Telnet for Microsoft Windows and Unix, along with an xterm terminal emulator. He is also ...
's C oriente
comprehensive introduction to coroutines

Softpanorama coroutine page
ontains extensive assembler coroutines links {{Authority control Concurrent computing Subroutines