Skip to main content
 首页 » 编程设计

python之react 堆比我预期的更早停止

2025年05月04日12Renyi-Fan

感谢this tutorial,我正在尝试自学一些基本的 Twisted 编程和许多其他人。我来到了这个当前示例,我无法弄清楚为什么它正在做它正在做的事情。

简短摘要:我已经实例化了三个 react 器,它们从 5 倒数到 1,并且在计数时有不同的延迟。唯一的问题是,看起来当第一个计数器(具有最短延迟)变为 0 时,它不仅停止了自己的 react 器,还停止了所有其他 react 器。

#!/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()