5

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?

Nathan Shively-Sanders
  • 18,329
  • 4
  • 46
  • 56
eonil
  • 83,476
  • 81
  • 317
  • 516

2 Answers2

4

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.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • 2
    +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 Aug 09 '10 at 01:10
  • It is also interesting to note coroutines work very much like processes (or OS threads) on a cooperative multitasking operating system. Every process runs on the CPU until it _yields_ back to the kernel at which point the OS saves the PC (and a bunch of other stuff), chooses another process to run and jumps to the PC previously saved for that process. Each process of course has it's own stack, as coroutines do. – Feuermurmel Feb 05 '14 at 17:09
2

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.)

Community
  • 1
  • 1
Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653