當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。