0

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.

Nathan
  • 8,093
  • 8
  • 50
  • 76
  • For what it's worth, there is no such thing as a "fiber" in Twisted. Fibers are a cooperative threading library for Windows - https://msdn.microsoft.com/en-us/library/windows/desktop/ms682661%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396 - and Twisted doesn't work in a similar way. – Glyph Dec 09 '15 at 00:41
  • I haven't been sure about what to call what Twisted does. That's why I put fiber in quotes. However, after reading https://en.wikipedia.org/wiki/Fiber_%28computer_science%29, it seems that fiber is the right word. It you have a better word, please share. – Nathan Dec 09 '15 at 17:39

1 Answers1

0

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)
Nathan
  • 8,093
  • 8
  • 50
  • 76