class Ractor::ClosedError

当尝试向已关闭的端口发送消息,或从已关闭且为空的端口检索消息时引发此异常。端口可以通过 Ractor#close_outgoing/close_incoming 显式关闭,并在 Ractor 终止时隐式关闭。

r = Ractor.new { sleep(500) }
r.close_outgoing
r.take # Ractor::ClosedError

ClosedErrorStopIteration 的子类,因此 ractor 的关闭将中断循环而不会传播错误。

r = Ractor.new do
  loop do
    msg = receive # raises ClosedError and loop traps it
    puts "Received: #{msg}"
  end
  puts "loop exited"
end

3.times{|i| r << i}
r.close_incoming
r.take
puts "Continue successfully"

这将打印

Received: 0
Received: 1
Received: 2
loop exited
Continue successfully