【发布时间】:2014-11-21 00:04:34
【问题描述】:
如果我在反应器事件循环中创建一个 Deferred 并为其添加一些回调,如果我让本地引用超出范围,它会被调用吗?例如,如果我有一个带有connectionMade() 的协议,如下所示:
def connectionMade(self):
# This made up function returns a deferred that will connect to
# some remote server using some made up protocol and return some data.
d = connectToRemoteServer(reactor, url)
d.addCallback(self._handleRemoteConnection)
# At this point, d is going to go out of scope, so will the deferred
# it points to ever get fired?
def _handleRemoteConnection(self, data):
# Do something with the data
我在使用 Twisted 的不同代码中看到了这种模式,但我无法理解为什么从 connectToRemoteServer() 返回的 deferred 不是
当 d 超出范围时收集垃圾。我认为它永远不会触发,或者由于竞争条件而随机失败。谁能向我解释为什么这有效?我已经读过http://twistedmatrix.com/documents/current/core/howto/defer.html 几遍了,但我仍然不确定为什么会这样?
谢谢,
卡尔
【问题讨论】:
-
对象在没有引用时被垃圾回收。因此,
d不是对该对象的唯一引用,因为它没有被垃圾回收。添加print(sys.getrefcount(d))...