【问题标题】:Twisted Python - If deferred goes out of scope, will it ever be fired?Twisted Python - 如果 deferred 超出范围,它会被解雇吗?
【发布时间】: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))...

标签: python twisted deferred


【解决方案1】:

假设的connectToRemoteServer API 将在内部持有对d 的引用,通常使用来自全局reactor 的引用,该对象将在操作时触发d(通过调用d.callback)由d 表示的是完整的。

所以引用从堆栈到reactor.run 的堆栈帧(因为反应器正在运行),到d

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多