tags:

views:

360

answers:

2

Hello, I have scratchy ideas of Generators, Iterators and Coroutines. (from PEPs and other tutorials). I want to implement a coroutine- in which routine1 will print odd and routine2 will print even numbers infinitely in a fashion such as:

routine1:
    print odd
    yield to routine2

routune2:
    print even
    yield to routine1

Have some rough ideas of the code that should do this, but not able to get it in shape. I do not want the code. But, I would appreciate pseudo code style pointers for the same. Thank you.

+1  A: 

You yield back to the method that called you. Hence you can't yield to routine 1. You just yield. You could let routine 1 call routine 2, and routine 2 can yield and hence return back to routine 1.

Lennart Regebro
I need to call routine1 form another place, right? Say, I call the routine1 from __main__, then it yields back to __main__, right ?
Amit
Correct. routine1 does not know that though. It just yields. So if you above wnat to routine1 to yield to routine2 you need to call it from routine2. And the other way around. And that would give you an infinite recursion where in fact nobody ever yields to anybody.
Lennart Regebro
+2  A: 

PEP 342, "Coroutines via Enhanced Generators", gives as its example 3 'A simple co-routine scheduler or "trampoline" that lets coroutines "call" other coroutines by yielding the coroutine they wish to invoke.' -- you don't need that much generality (or any of the generality aspects PEP 342 first introduced), for this very specific task, given that the coroutines are not communicating anything to each other, there's only two of them, their order of succession is perfectly regular, there is no termination, etc, etc... but a small subset of that code is still worth implementing as it shows you more about coroutines than this extremely simple example could on its own.

The two coroutines should probably be two instances from the same generator function differing just in starting point (no point in writing that while True: loop twice after all, given how simple its body will be;-). As you'll see, the interesting part is the trampoline, even though you can and should make it vastly simpler than the general one in PEP 342.

Alex Martelli