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


Ruby Ractor.send用法及代碼示例

本文簡要介紹ruby語言中 Ractor.send 的用法。

用法

send(msg, move: false) → self
也別名為:<<

向 Ractor 的傳入隊列發送消息以供 Ractor.receive 使用。

r = Ractor.new do
  value = Ractor.receive
  puts "Received #{value}"
end
r.send 'message'
# Prints: "Received: message"

該方法是非阻塞的(即使 ractor 還沒有準備好接收任何東西,也會立即返回):

r = Ractor.new {sleep(5)}
r.send('test')
puts "Sent successfully"
# Prints: "Sent successfully" immediately

嘗試發送到已經完成執行的 ractor 將引發 Ractor::ClosedError

r = Ractor.new {}
r.take
p r
# "#<Ractor:#6 (irb):23 terminated>"
r.send('test')
# Ractor::ClosedError (The incoming-port is already closed)

如果 close_incoming 在 ractor 上被調用,該方法也會引發 Ractor::ClosedError

r =  Ractor.new do
  sleep(500)
  receive
end
r.close_incoming
r.send('test')
# Ractor::ClosedError (The incoming-port is already closed)
# The error would be raised immediately, not when ractor will try to receive

如果 obj 不可共享,默認情況下它將通過深度克隆複製到 ractor。如果傳遞了move: true,則對象是moved 進入ractor,並且發送者無法訪問。

r = Ractor.new {puts "Received: #{receive}"}
msg = 'message'
r.send(msg, move: true)
r.take
p msg

這打印:

Received: message
in `p': undefined method `inspect' for #<Ractor::MovedObject:0x000055c99b9b69b8>

所有對對象及其部分的引用在發送者中都將變為無效。

r = Ractor.new {puts "Received: #{receive}"}
s = 'message'
ary = [s]
copy = ary.dup
r.send(ary, move: true)

s.inspect
# Ractor::MovedError (can not send any methods to a moved object)
ary.class
# Ractor::MovedError (can not send any methods to a moved object)
copy.class
# => Array, it is different object
copy[0].inspect
# Ractor::MovedError (can not send any methods to a moved object)
# ...but its item was still a reference to `s`, which was moved

如果對象是可共享的,move: true 對其沒有影響:

r = Ractor.new {puts "Received: #{receive}"}
s = 'message'.freeze
r.send(s, move: true)
s.inspect #=> "message", still available

相關用法


注:本文由純淨天空篩選整理自ruby-lang.org大神的英文原創作品 Ractor.send。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。