Search code examples
smalltalkcoroutine

How are coroutines implemented in smalltalk?


Can I implement coroutines in smalltalk?

If your answer is no: why not?

Or if its yes: can you give me an example?


Solution

  • Most Smalltalk have stack manipulation methods on the thisContext object. You could use these to implement coroutines though dealing with the stack at this level may prove a bit tedious.

    GNU Smalltalk and recent versions of Squeak and Pharo also offer a Generator class that makes it easy to write generators (i.e. types of coroutine that yield multiple values):

    "This generator yield an infinite sequence of 1"
    generator := Generator on: [ :gen | [ gen yield: 1 ] repeat ].
    
    (1 to: 100) do: [:i | Transcript show: (generator next printString); cr]