views:

92

answers:

2

I have a question about coroutine implementation. I saw coroutine first on Lua and stackless-python. I could understand the concept of it, and how to use yield keyword, but I cannot figure out how it is implemented.

Can I get some explanation about them?

+3  A: 

Coroutining is initiated by pushing the target address, then each coroutine switch exchanges the current PC with the top of the stack, which eventually has to get popped to terminate the coroutining.

EJP
+1, this is the way to do it if you have access to the stack like you do in C or most Smalltalks (or if you have implemented *your own* stack, which is basically what Stackless Python and the Lua VM do).
Jörg W Mittag
+1  A: 

See also: Implementing “Generator” support in a custom language. Generators are basically a limited form of (semi-)coroutines, most of what is discussed in that question applies here as well.

Also: How are exceptions implemented under the hood? While exceptions are obviously very different from coroutines, they both have something in common: both are advanced universal control flow constructs. (In fact, you can implement coroutines using exceptions and exceptions using coroutines.)

Jörg W Mittag