当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Ruby Fiber.transfer用法及代码示例


本文简要介绍ruby语言中 Fiber.transfer 的用法。

用法

transfer(args, ...) → obj

将控制权转移到另一根光纤,从上次停止的地方恢复它,如果之前没有恢复,则启动它。调用光纤将被暂停,就像调用 Fiber.yield 一样。

接收转接调用的光纤将其视为恢复调用。传递给 transfer 的参数被视为传递给 resume 的参数。

传入和传出光纤的两种控制方式(一种是 resume Fiber::yield ,另一种是传入和传出光纤的 transfer )不能自由混合。

  • 如果 Fiber 的生命周期从传输开始,它将永远无法让步或恢复控制传递,只能完成或传输回。 (它仍然可以恢复其他允许恢复的光纤。)

  • 如果 Fiber 的生命周期从 resume 开始,它可以让出或转移到另一个 Fiber ,但只能以与它被放弃的方式兼容的方式接收控制权:如果它已经转移,它只能被转移返回,并且如果它已经屈服,它只能恢复返回。之后,它再次可以转移或屈服。

如果违反了这些规则,则会引发 FiberError

对于单独的 Fiber 设计,yield/resume更容易使用( Fiber 只是放弃控制权,不需要考虑控制权给谁),而对于复杂的情况,传输更灵活,允许构建相互依赖的 Fibers 的任意图。

例子:

manager = nil # For local var to be visible inside worker block

# This fiber would be started with transfer
# It can't yield, and can't be resumed
worker = Fiber.new { |work|
  puts "Worker: starts"
  puts "Worker: Performed #{work.inspect}, transferring back"
  # Fiber.yield     # this would raise FiberError: attempt to yield on a not resumed fiber
  # manager.resume  # this would raise FiberError: attempt to resume a resumed fiber (double resume)
  manager.transfer(work.capitalize)
}

# This fiber would be started with resume
# It can yield or transfer, and can be transferred
# back or resumed
manager = Fiber.new {
  puts "Manager: starts"
  puts "Manager: transferring 'something' to worker"
  result = worker.transfer('something')
  puts "Manager: worker returned #{result.inspect}"
  # worker.resume    # this would raise FiberError: attempt to resume a transferring fiber
  Fiber.yield        # this is OK, the fiber transferred from and to, now it can yield
  puts "Manager: finished"
}

puts "Starting the manager"
manager.resume
puts "Resuming the manager"
# manager.transfer  # this would raise FiberError: attempt to transfer to a yielding fiber
manager.resume

produces

Starting the manager
Manager: starts
Manager: transferring 'something' to worker
Worker: starts
Worker: Performed "something", transferring back
Manager: worker returned "Something"
Resuming the manager
Manager: finished

相关用法


注:本文由纯净天空筛选整理自ruby-lang.org大神的英文原创作品 Fiber.transfer。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。