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


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。