Python 反应堆停得比我预期的要早?

Python 反应堆停得比我预期的要早?,python,twisted,Python,Twisted,我正试图教自己一些基本的扭曲编程,多亏了和许多其他人。我已经来到了这个当前的例子,我不明白为什么它在做它正在做的事情 简短总结:我列举了三个反应堆,它们从5倒计时到1,并且在计数过程中有不同的延迟。唯一的问题是,当第一个计数器(延迟最短)达到0时,它不仅停止自己的反应器,而且停止所有其他的反应器 #!/usr/bin/env python class Countdown(object): counter = 5 def count1(self): from

我正试图教自己一些基本的扭曲编程,多亏了和许多其他人。我已经来到了这个当前的例子,我不明白为什么它在做它正在做的事情

简短总结:我列举了三个反应堆,它们从5倒计时到1,并且在计数过程中有不同的延迟。唯一的问题是,当第一个计数器(延迟最短)达到0时,它不仅停止自己的反应器,而且停止所有其他的反应器

#!/usr/bin/env python

class Countdown(object):

    counter = 5

    def count1(self):
        from twisted.internet import reactor
        if self.counter == 0:
            reactor.stop()
        else:
            print self.counter, '...1'
            self.counter -= 1
            reactor.callLater(1, self.count1)

    def count2(self):
        from twisted.internet import reactor
        if self.counter == 0:
            reactor.stop()
        else:
            print self.counter, '...2'
            self.counter -= 1
            reactor.callLater(0.5, self.count2)

    def count3(self):
        from twisted.internet import reactor
        if self.counter == 0:
            reactor.stop()
        else:
            print self.counter, '...3'
            self.counter -= 1
            reactor.callLater(0.25, self.count3)

from twisted.internet import reactor

reactor.callWhenRunning(Countdown().count1)
reactor.callWhenRunning(Countdown().count2)
reactor.callWhenRunning(Countdown().count3)

print 'Start!'
reactor.run()
print 'Stop!'
输出

Start!
5 ...1
5 ...2
5 ...3
4 ...3
4 ...2
3 ...3
2 ...3
4 ...1
3 ...2
1 ...3
Stop!

我的印象是,虽然所有三个计数器都应该以自己的速度倒计时并完成其5->0进程,但程序会等待它们全部完成,然后退出。我在这里误解了Twisted的某些内容吗?

我不熟悉Twisted,但从谷歌搜索结果来看,reactor似乎是一个事件循环。您只有一个计数器,因此第一个命中reactor.stop()的计数器将停止循环


要想做你想做的事情,你需要移除reactor.stop()调用并构造一些东西,这样当最后一个计时器到达末尾时,它(并且只有它)调用reactor.stop(),他在中谈到了这一点。您可能混淆了“在一台服务器中启动三个反应器”和“启动三个不同的服务器”。这些例子建议做后者;您的代码正在尝试执行前者

基本上,反应堆是一个循环,一旦停止,就不能重新启动。所以每个进程只能有一个,或者每个线程只能有一个


您不需要启动三个反应器,而是希望在同一个反应器上设置三个不同的定时回调。他们都会在适当的时候被解雇。

Brian,谢谢你的提示。也许我对Twisted的方法还不够熟悉,但是如何编写一个查找“最后一个计时器”的条件语句呢?我曾想过使用getDelayedCalls,但这似乎只适用于callLater用法,而不适用于运行时的CallWhen。