本文简要介绍ruby语言中 Ractor.receive
的用法。
用法
receive → msg
也别名为:recv
从当前 Ractor 的传入端口队列接收传入消息,该消息由 send
发送到那里。
r = Ractor.new do
v1 = Ractor.receive
puts "Received: #{v1}"
end
r.send('message1')
r.take
# Here will be printed: "Received: message1"
或者,可以使用私有实例方法receive
:
r = Ractor.new do
v1 = receive
puts "Received: #{v1}"
end
r.send('message1')
r.take
# Here will be printed: "Received: message1"
如果队列为空,该方法将阻塞。
r = Ractor.new do
puts "Before first receive"
v1 = Ractor.receive
puts "Received: #{v1}"
v2 = Ractor.receive
puts "Received: #{v2}"
end
wait
puts "Still not received"
r.send('message1')
wait
puts "Still received only one"
r.send('message2')
r.take
输出:
Before first receive Still not received Received: message1 Still received only one Received: message2
如果在 ractor 上调用了 close_incoming
,则如果传入队列中没有更多消息,该方法将引发 Ractor::ClosedError
:
Ractor.new do
close_incoming
receive
end
wait
# in `receive': The incoming port is already closed => #<Ractor:#2 test.rb:1 running> (Ractor::ClosedError)
相关用法
- Ruby Ractor.receive_if用法及代码示例
- Ruby Ractor.close_incoming用法及代码示例
- Ruby Ractor.count用法及代码示例
- Ruby Ractor.shareable?用法及代码示例
- Ruby Ractor.current用法及代码示例
- Ruby Ractor.new用法及代码示例
- Ruby Ractor.close_outgoing用法及代码示例
- Ruby Ractor.yield用法及代码示例
- Ruby Ractor.send用法及代码示例
- Ruby Ractor.take用法及代码示例
- Ruby Ractor.make_shareable用法及代码示例
- Ruby Ractor.select用法及代码示例
- 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.receive。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。