本文简要介绍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 Ractor.select用法及代码示例
- Ruby Ractor.shareable?用法及代码示例
- Ruby Ractor.receive_if用法及代码示例
- Ruby Ractor.close_incoming用法及代码示例
- Ruby Ractor.count用法及代码示例
- Ruby Ractor.current用法及代码示例
- Ruby Ractor.new用法及代码示例
- Ruby Ractor.receive用法及代码示例
- Ruby Ractor.close_outgoing用法及代码示例
- Ruby Ractor.yield用法及代码示例
- Ruby Ractor.take用法及代码示例
- Ruby Ractor.make_shareable用法及代码示例
- Ruby Ractor类用法及代码示例
- Ruby Racc模块用法及代码示例
- Ruby Range.end用法及代码示例
- Ruby Range new()用法及代码示例
- Ruby Rational.inspect用法及代码示例
- Ruby Random.bytes用法及代码示例
- Ruby Random hex()用法及代码示例
- Ruby Range.size用法及代码示例
- Ruby Rational.rational <=>用法及代码示例
- Ruby Rational to_i()用法及代码示例
- Ruby Rational.rat ** numeric用法及代码示例
- Ruby Random random_number()用法及代码示例
- Ruby Range last()用法及代码示例
注:本文由纯净天空筛选整理自ruby-lang.org大神的英文原创作品 Ractor.send。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。