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


Ruby Ractor.take用法及代码示例


本文简要介绍ruby语言中 Ractor.take 的用法。

用法

take → msg

从 ractor 的传出端口获取一条消息,该消息由 Ractor.yield 或在 ractor 的最终确定时放置在那里。

r = Ractor.new do
  Ractor.yield 'explicit yield'
  'last value'
end
puts r.take #=> 'explicit yield'
puts r.take #=> 'last value'
puts r.take # Ractor::ClosedError (The outgoing-port is already closed)

最后一个值也被放入传出端口的事实意味着 take 可以用作 Thread#join 的一些模拟(“等到 ractor 完成”),但不要忘记如果有人已经消费它会引发ractor 所生产的一切。

如果传出端口用 close_outgoing 关闭,该方法将引发 Ractor::ClosedError

r = Ractor.new do
  sleep(500)
  Ractor.yield 'Hello from ractor'
end
r.close_outgoing
r.take
# Ractor::ClosedError (The outgoing-port is already closed)
# The error would be raised immediately, not when ractor will try to receive

如果在 Ractor 中引发未捕获的异常,它会作为 Ractor::RemoteError 传播。

r = Ractor.new {raise "Something weird happened"}

begin
  r.take
rescue => e
  p e              #  => #<Ractor::RemoteError: thrown by remote Ractor.>
  p e.ractor == r  # => true
  p e.cause        # => #<RuntimeError: Something weird happened>
end

Ractor::ClosedError StopIteration 的后代,因此关闭 ractor 将打破循环而不传播错误:

r = Ractor.new do
  3.times {|i| Ractor.yield "message #{i}"}
  "finishing"
end

loop {puts "Received: " + r.take}
puts "Continue successfully"

这将打印:

Received: message 0
Received: message 1
Received: message 2
Received: finishing
Continue successfully

相关用法


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