gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 06:30:10 25 4
gpt4 key购买 nike

感谢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()

关于python - react 堆比我预期的更早停止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3851899/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com