22

Is there a way to stop the twisted reactor when a certain condition is reached. For example, if a variable is set to certain value, then the reactor should stop?

gmemon
  • 2,573
  • 5
  • 32
  • 37

2 Answers2

32

Ideally, you wouldn't set the variable to a value and stop the reactor, you'd call reactor.stop(). Sometimes you're not in the main thread, and this isn't allowed, so you might need to call reactor.callFromThread. Here are three working examples:

# in the main thread:
reactor.stop()

# in a non-main thread:
reactor.callFromThread(reactor.stop)

# A looping call that will stop the reactor on a variable being set, 
# checking every 60 seconds.
from twisted.internet import task
def check_stop_flag():
    if some_flag:
        reactor.stop()
lc = task.LoopingCall(check_stop_flag)
lc.start(60)
Matthew Murdoch
  • 30,874
  • 30
  • 96
  • 127
Jerub
  • 41,746
  • 15
  • 73
  • 90
  • The looping call example is what I was looking for. Still, it will be great if an event can be added to the reactor that says when some_flag is set, call some_method, which will call reactor.stop. – gmemon Jun 30 '11 at 00:00
  • Thank you for posting this. One wonders why reactor.stop() doesn't default to calling from the main thread... it seems like unnecessary complication but I'm sure there was an underlying reason for it. – wickedchicken Apr 24 '12 at 07:53
  • Twisted APIs are not thread-safe. That's a simpler blanket approach than having some seemingly random subset be safe to call from any thread (that would leave you perpetually referring to the documentation for any particular API you want to use to determine if it is safe). And it is impractical to make all APIs thread-safe (runtime overhead is prohibitive, and implementation becomes very complicated in some cases, and the APIs themselves get more complicated - eg, what thread are a factory's methods called in, if the factory is used with connectTCP in a non-reactor thread?). – Jean-Paul Calderone Jun 06 '12 at 20:03
7

sure:

if a_variable == 0:
    reactor.stop()
Gerrat
  • 28,863
  • 9
  • 73
  • 101