Talk:Coroutine

message: Doesn't Ruby have coroutines? Someone should mention that. --68.35.244.188 05:25, 12 Aug 2004 (UTC)
replies: text: I am not expert in Ruby, but I believe it has only continuations, not coroutines as such. There is a slight difference. Samohyl Jan 05:32, 10 September 2007 (UTC)
thread_title:  Ruby coroutines 

message: The author of this article clearly has a preference for coroutines over the more popular structures in modern, commercial programming languages.  Popularity is by no means a justification for something.  However, in this case the alternatives to coroutines are popular for good reason.
Coroutines allowed the "thread of execution", however it is implemented, to enter a function, process it for a while, return to the caller, and go back to the function where it left off while maintaining the state of local variables.  This all sounds very useful.  It is not.  There are much better ways of accomplishing whatever task you wish to perform.  I will address some of the issues the author mention above.
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.
It is true that most procedural and object-oriented programming languages don't let you jump to the middle of a function.  You can in standard Pascal using a goto statement, but it is a bad practice.  It is such a bad practice that Borland prohibited it in its Turbo Pascal compiler.
Object-oriented languages such as Java and C++ provide a far more elegant solution.  Encapsulate the state information and the operations in a class.  The internal state persists between calls to the method because the internal state is associated with members of the class.
: Object-oriented languages do not specifically provide a more elegant solution.  You might as well argue that threads as a whole are unnecessary because you can model any number of threads in your application instead with a state machine.  This is not eloquent -- using a state machine imperatively to simulate threads.  It is much better and easier to write each object such that each object /believes/ it is in its own thread.  This is much more natural than writing state machines.  You should consider reading: http://www.stackless.com/ —Preceding unsigned comment added by 24.175.26.71 (talk • contribs) 2005-10-07 06:43:25
Threads resemble coroutines on steroids. 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 seems like overkill.
I do not consider threads to be complex, difficult to learn how to use, or overkill.  Multithreaded programming was always simpler than using interprocess communication.  In languages like Java, multithreading is extremely simple and easy to use.  Two lines of code.
 Thread myThread = new Thread(objectThatImplementsRunnable, "My Thread's Name");
 myThread.start();
You can even combine these two lines of code into one if you like.  So easy.  And despite being so easy, threads are extremely efficient.  Context switching is almost non-existent in threads.  Plus you get pre-emptive multitasking, thread priority, and suspend/resume capability for free.
Threads and object-oriented programming are the way to go.  Coroutines may be a nifty concept, but they can't do anything that threads and classes can't do more eloquently.
: Coroutines are for many tasks easier than threads. Consider for instance you want to program a state machine. Without threads or coroutines, you need to remember state, and with each call of the procedure implementing state machine make a jump by the state. This will result in somewhat clumsy and hard-to-read code, because entry point must know how to deal with all states, not only outgoing ones. With threads, you could do this, but you also have to explicitly synchronize them (because you really don't need concurrency for this task). But coroutines make implementation of this easy and natural. For instance, this can be used to program agents in games, where each agent is essentially a state machine, and they interact. Then it nicely separates code for each agent from the rest (main loop), without hassle about synchronization and locking, because they are in fact executed sequentially. Samohyl Jan 10:36, 26 August 2005 (UTC)
replies: text:  I agree with this.  You're missing the point if you think that coroutines and threads are tools for the same purpose.  They are most certainly not.  Pointedly, coroutines can be used (such as in Stackless Python) to provide thread-like behavior for a massive number of independent objects.  For example, you could have 100,000 objects each of which is written in a thread-like manner.  No real OS could manage that number of threads in a practical way.  However, you can write such a system with coroutines.  Note that your result is effectively cooperative multitasking, where threads traditionally use pre-emptive multitasking. —Preceding unsigned comment added by 24.175.26.71 (talk • contribs) 06:40, 7 October 2005 (UTC)
thread_title:  Editorial 

message: BLISS programming language - what about this ? —Preceding unsigned comment added by 195.42.89.34 (talk • contribs) 2005-12-29 13:35:45
??? For that matter, they originated before BLISS. They were a recognized assembly-language technique. In fact I think that's how Knuth presents coroutines. Dpbsmith (talk) 14:46, 29 December 2005 (UTC)
thread_title:  Coroutines originated in languages Simula and Modula-2, 

message: Does the yield return statement in C# fit in here? 220.245.146.199 11:47, 13 September 2007 (UTC)
replies: text: If it specifies where it's yielding to, then yes; otherwise, add it to generator (computer science). EdC 21:43, 13 September 2007 (UTC)
thread_title:  C# yield return statement 

message: The definition of Green Threads seems identical to the historic definition of Coroutines. Only if you insist that a Coroutine cannot suspend in a subroutine (i.e. suspend when there is call stack or context) would there be any difference.
The term Green Thread is quite "new". Coroutines in Simula (and early C++ versions) worked exactly like Green Threads. DRW - Oct 8, 2007  —Preceding unsigned comment added by 207.59.232.138 (talk) 15:55, 8 October 2007 (UTC)
replies: text: See green threads linas (talk) 16:01, 22 August 2009 (UTC)
thread_title:  Green Thread? 

message: Tcl 8.6 will have coroutines; I've not added it to the list of programming languages yet because that's still a version in beta. Of course, it strictly has generators, but the generator semantics allows the passing of a value upon reentry after yield and a bunch of other things that makes the functionality more coroutine like, and many other languages are in the list despite being generators as well. Note that we won't have a direct “yield to”; that's considered to not fit with the way that the rest of the language operates. Donal Fellows (talk) 15:15, 8 January 2009 (UTC)
thread_title:  Coroutines in Tcl 

message: FYI, I just came across a very nice, very simple, elegant example implementation of coroutines in scheme, using just a continuation and a queue, and posted it on the Talk:Continuation page.  I think it deserves to be in some article somewhere, just not sure where. linas (talk) 15:58, 22 August 2009 (UTC)
thread_title:  Coroutine in Scheme 

message: I would like to consistently use  tempalates and {{Reflist|refs=... in this article. The former for consistency and the latter for decluttering the text. I've started on this effort and plan to continue if there are no objections; so feel free to revert and set me straight here! Thanks, ErikHaugen (talk) 21:00, 26 October 2010 (UTC)
thread_title:  reference style 

message: For anyone feeling that the historical role of Ralph Griswold et al Icon programming language is not given its due here, I would note the recent changes to the implementation in Robert Parlett's ObjectIcon at code.google.com/p/objecticon
I have added a link to CLU at the Icon article
G. Robert Shiplett 00:06, 16 June 2012 (UTC)
thread_title:  coexpressions in Icon 

message: Coroutines are a useful pattern for game development. In this area, one often wants to expose a scripting-language to designers or developers, without giving them access to threading mechanisms which require careful tuning and centralized control for high-performance. The rendering-frame or simulation frame (typically from 15 Hz to 60 Hz) means that most tasks need to be broken-up into actions that can happen in (much) less than the frame time. Storing state in objects, as mentioned in the editorial section, is one way to do this, but leads to a proliferation of boiler-plate code. For instance, creating state enums, switching on the object's current state, etc. Code can be clearer, and therefore more maintainable if it is visible at a glance, has straight-line flow, and is contained in a few-line coroutine, rather than dispersed through multiple locations in the sources.
Coroutines in the Unity Game Engine: http://docs.unity3d.com/Documentation/Manual/Coroutines.html
Coroutines in Lua (an often used extension-language for games): http://www.lua.org/pil/9.1.html
Jawa0 (talk) 15:20, 1 November 2013 (UTC)
thread_title:  Use in Game Development 

message: The external links section contains a stale reference to [explanation of coroutines. This URL no longer works. JR Bouvier (talk) 17:49, 30 December 2013 (UTC)
replies: text: I removed it; feel free to fix stuff. ErikHaugen (talk | contribs) 18:43, 30 December 2013 (UTC)
thread_title:  Stale external link 

message: I can't make sense of this sentence:
: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 latter is entered in the same continuous manner as the former.
Also, the term "yield" is not properly introduced before it's used.
Encyclopedant (talk) 23:45, 4 August 2014 (UTC)
thread_title:  Clarification please 

message: Hello fellow Wikipedians,
I have just modified  on Coroutine. Please take a moment to review my edit. If you have any questions, or need the bot to ignore the links, or the page altogether, please visit this simple FaQ for additional information. I made the following changes:
*Corrected formatting/usage for http://www.ruby-forum.com/topic/126011
When you have finished reviewing my changes, please set the checked parameter below to true or failed to let others know (documentation at ).
Cheers.—cyberbot IITalk to my owner:Online 01:35, 1 April 2016 (UTC)
thread_title:  External links modified 

message: You say that generators are weaker since their yield supplies no label to jump to. You immediately demonstrate that `yield to consumer` can be emulated with generators by `yield consumer`. This is a joke to me. You had to drop `to consumer` instead of only `to` particle in order to transform the code into generators. How does dropping `to` particle work? --Javalenok (talk) 06:25, 7 December 2016 (UTC)
thread_title:  Emulating with trampoline 

message: A new entry is needed under the C++ section, namely the coroutines TS (technical specification). It proposes a C++ standard for stackless coroutines that will very likely be in C++20.  Three major compilers, Visual C++, gcc, and Clang already support major portions, in the std::experimental namespace. Here's a link to the TS: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/n4680.pdf  — Preceding unsigned comment added by 2600:1700:E840:AC40:64DB:84F0:639C:A8E3 (talk) 00:02, 29 March 2018 (UTC)
thread_title:  C++ coroutines TS 

message: While seeking information, I found a questionable citation that I replaced with a better URL, which only illustrates a technique. The questionable citation was introduced in 2013. --Ancheta Wis    (talk  | contribs) 13:36, 13 January 2019 (UTC)
thread_title:  Programming languages with native support 

message: What are the defining features of a coroutine? (How do different authors theoretically define coroutines, and do different major programming languages differ in what sort of object is/isn't termed a coroutine?)
For example are all these neccessary and sufficient for a block of code to be a general coroutine:
* Multiple entry points (not only the beginning of the block). (Is this always implemented as a statement that temporarily yields control then resumes at the following line?)
* Repeated bidirectional information passing i.e. the code can send new information each time it yields control, and can receive new information each time it resumes execution. (Presumably this piece of information is always sent to/from the same section of code as which control is passing to/from at that same instant?) 
* Retention of state (local variables) while the block of code is suspended. (Is this implemented differently from the typical stack?)
* Ability for that block of code to yield control to other than its own caller. (?)
How are coroutines different from subroutines that call other subroutines? (I.e. a call statement cooperatively passes control to someplace else, and later the execution may resume from the next line). Is the difference that subroutines have a hierarchical stack structure (i.e. a subroutine can call a new subroutine or return to its own caller, but cannot directly pass control back to another routine that is deeper in the call stack)? Do coroutines facilitate flow graphs containing cycles?
Does "coroutine" have any meaning in entirely functional, rather than proceedural, programming paradigms (say, Lisp, Mathematica)? 
In object-oriented programming, is message-passing (method calling) between objects a full implementation of coroutines? (Is it a problem that calling a send/receive method will always pass control to the start of that method?)
Does making full use of coroutines require launching them from an event loop (like in Python)?
The original 1963 coroutines paper seems to describe communication between coroutines as analogous (in syntax) to how a traditional program makes IO (read/write) calls. They were intended for multistage data processing pipelines, letting different-stage modules run concurrently/asynchronously so that data can be streamed through the entire pipeline in a single pass (akin to nesting generators in Python) without needing to cache any intermediate dataset in full. Is the coroutine concept more general than nested generators?
Cesiumfrog (talk) 02:33, 5 September 2019 (UTC)
replies: text: I had the same confusion. But I've added section Definition and Types lately. You may take a look. Thanks. Gqqnb (talk) 12:37, 28 January 2023 (UTC)
thread_title:  Definition 

message: The Comparison with threads section contains
: 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 or any blocking calls whatsoever), there is no need for synchronisation primitives such as mutexes, semaphores, etc. in order to guard critical sections, and there is no need for support from the operating system.
I'm not sure what would be the best way to fix it, but I don't think this is correct. Hard realtime just means that missing the deadline is an error, i.e. never occurs if the software is correct, as opposed to only degrading performance or quality in some way. Some systems have synchronisation primitives, including mutexes, with operations that can be guaranteed to complete in a bounded amount of time, which means they can be used with no risk of missing a deadline.
--119.18.1.113 (talk) 03:25, 27 August 2020 (UTC)
replies: text: Good points. An issue I see is that the section seems to imply that threads cannot (at all) be used in hard-realtime contexts, and that coroutines are the (only?) way to go. Maybe it could be rewritten so that coroutines are portrayed as one way of switching context (with little OS support) these systems. Chrisma0 (talk) 08:55, 27 August 2020 (UTC)
thread_title:  Coroutines vs Threads in hard realtime contexts 

message: In reading this article on coroutines, it appears to me that this term does not mean what it did 50 years ago. I would like to direct everyone's attention to an article called Moving FORTH  by Brad Rodriguez. If you look at the section called Indirect Threaded Code you will see three short routines called NEXT, ENTER and EXIT which are truly coroutines. They do not call each other they simply jump to each other based on the code being handled. While the code is executing a function these three coroutines bounce back and forth between the three of them. When the DUP code is called a different coroutine is executed in place of ENTER, and when it completes it jumps back to NEXT without invoking EXIT.  If a data element is called, the coroutine for that data element's type is called in place of ENTER. In this way they allow the Virtual Machine they are in to operate efficiently. There are NO subroutine calls involved. The return stack never gets an address to return to one of these routines. There is a return stack being used, but it is associated with the position in the bytecode routine being scanned. I believe that these coroutines exemplify the meaning of what it means to be a coroutine.
If you go back and investigate who was on the team that wrote the COBOL compiler with Melvin Conway (who authored the referenced article [2] which gave coroutines their name) you will probably find Chuck Moore the author of FORTH whose work inspired the Moving FORTH article. 
50.206.176.154 (talk) 01:23, 22 April 2021 (UTC)
thread_title:  Lost History? 

message: There are 2 different 'basic' types of coroutine.
* Symmetric coroutines. There is only one operator, `yield to`, and this transfers control to another coroutine.
* Asymmetric coroutines. There are two operators, `resume` and `yield`. `resume` transfers control to another coroutine, and then control is transferred back when it performs a `yield`.
There are two more potential distinctions between types of coroutine.
* Stackful coroutines. You can use `resume`/`yield`/`yield to` within a function call, and when the coroutine recieves control again it continues from within that function call. Yielded coroutines retain their own call stack.
* Stackless coroutines. You cannot use `yield` or `yield to` within a function call. Yielded coroutines do not retain their own call stack.
There is another distinction which only applies to asymmetric coroutines.
* Output-only coroutines. `resume` cannot transfer values into the coroutine, but `yield` can transfer them out.
* Input-output coroutines. Both `resume` and `yield` can transfer values.
This article confuses these distinctions in some way. In the section comparing 'coroutines' with 'generators', it defines 'coroutine' as referring to symmetric coroutines, and 'generator' as referring to asymmetric ones. It seems to imply that 'coroutines' are more expressive than 'generators', and I would disagree, but that's a subjective matter.
Later on in the article, languages like Lua, Python and JavaScript are considered to have 'coroutines'. Both of these languages actually have asymmetric, input-output coroutines, which this article considers 'generators'. These ought to be mentioned in the Generator article, but they're not, they're here.
Python's section in the article implies that the 'generator'/'coroutine' distinction is one of output-only/input-output, rather than symmetric/asymmetric as was defined earlier. This seems to be how the Python community defines the distinction, but this discrepancy should be mentioned.
Overall, this article is very inconsistent and conflates several different flavours of coroutine with each other. This was inevitable as the terminology is completely inconsistent in general usage, and seems to vary between languages. However, both this article and the Generator article should inform about these inconsistencies, rather than feeding into them. Rdococ1 (talk) 18:37, 4 February 2022 (UTC)
replies: text: I agree. The academia doesn't have a common definition of coroutine, which leads to the loose logic of this article. What's more, people also have divided views of whether the coroutine in a language, eg. Python, is stackful or stackless. Gqqnb (talk) 04:24, 31 October 2022 (UTC)
thread_title:  Coroutine/generator terminology confusion