Skip to content Skip to sidebar Skip to footer

Python Loop In A Coroutine

I've read all the documentation on the subject, but it seems I can't grasp the whole concept of Python coroutines well enough to implement what I want to do. I have a background ta

Solution 1:

If you look at the (trivial) coroutine.py library you're using, it includes an example that shows how grep works "in the background". There are two differences between your code and the example:

  1. grep repeatedly yields while doing its work—in fact, it yields once per line. You have to do this, or nobody but your coroutine gets a chance to run until it's finished.

  2. the main code repeatedly calls send on the grep coroutine, again once per line. You have to do this, or your coroutines never get called.

This is about as trivial a case as possible—a single coroutine, and a trivial dispatcher that just unconditionally drives that one coroutine.

Here's how you could translate your example into something that works:

@coroutinedefsomeroutine():
    withopen('test.txt', 'a') as f:
        yield
        f.write('A')
    whileTrue:
        yieldyield0

routine = someroutine()
print'I am working in parallel!'
routine.send()
print'But only cooperatively...'
routine.send()

And so on.

But normally you don't want to do this. In the case of the grep example, the coroutine and the main driver are explicitly cooperating as a consumer and producer, so that direct coupling makes perfect sense. You just have some completely independent tasks that you want to schedule independently.

To do that, don't try to build threading yourself. If you want cooperative threading, use an off-the-shelf dispatcher/scheduler, and the only change you have to make to all of your tasks is to put in yield calls often enough to share time effectively.

If you don't even care about the threading being cooperative, just use threading or multiprocessing, and you don't even need the yields:

defsomeroutine():
    withopen('test.txt', 'a') as f:
        f.write('A')
    whileTrue:
        passreturn0

routine = threading.Thread(someroutine)
print'I am working in parallel!'

PS, as I said in one of the comments, if you haven't worked through http://www.dabeaz.com/coroutines/index.html or an equivalent, you really should do that, and come back with any questions you find along the way, instead of writing code that you don't understand and asking why it doesn't work. I'm willing to bet that if you make it to part 4 (probably even earlier), you'll see why your initial question was silly.

Solution 2:

while True: pass

ENDLESS LOOP.

So it will not execute yeld after that. In fact its real end of function, everything after that is pure useless decoration.

And since someroutine get STUCK before it can yeld (pun intended ;) ), yeld someroutine() will also not yeld.

So you get your script busily doing nothing. (infinite empty loop).

Post a Comment for "Python Loop In A Coroutine"