python-2.7twistedfiber

Stop a Twisted Fiber Mid-Execution


There are many ways to create a Python Twisted fiber. For example, one could call reactor.callWhenRunning(helloWorld). helloWorld() will execute and the fiber will stop executing when helloWorld() returns.

What if half way through executing helloWorld() I wanted to stop the fiber's execution without impacting the rest of the fibers? How would I do that?

If the execution is inside helloWorld() itself, then I could simply return from the method. But, what if the program is 10 nested calls deep? How would I stop the fiber's execution from continuing? I suppose I could make all 10 methods return immediately but that would be very difficult to code for a large program with 1000s of methods.

I could raise an exception. This would work unless some method in the call stack (besides the reactor) catches the exception.

I could do the following. However, this will add a lot of pending Deferreds to pile up in the Twisted reactor.

while True:
    d       = defer.Deferred()
    d.delay = reactor.callLater(sys.maxint, d.callback, None)

    yield d

Are there any other solutions?

Note: A Python 2.6 solution would be ideal.


Solution

  • The solution is to simply call cancel() on the Deferred before yielding. The code does not continue execution after the yield.

    d       = defer.Deferred()
    d.delay = reactor.callLater(sleepTime, d.callback, None)
    
    d.cancel()
    
    yield d
    returnValue(None)