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


Ruby Ractor.receive_if用法及代码示例


本文简要介绍ruby语言中 Ractor.receive_if 的用法。

用法

receive_if {|msg| block } → msg

仅接收特定消息。

代替 Ractor.receive Ractor.receive_if 可以按块提供模式,您可以选择接收消息。

r = Ractor.new do
  p Ractor.receive_if{|msg| msg.match?(/foo/)} #=> "foo3"
  p Ractor.receive_if{|msg| msg.match?(/bar/)} #=> "bar1"
  p Ractor.receive_if{|msg| msg.match?(/baz/)} #=> "baz2"
end
r << "bar1"
r << "baz2"
r << "foo3"
r.take

这将输出:

foo3
bar1
baz2

如果块返回真值,则消息将从传入队列中删除并返回。否则,消息将保留在传入队列中,并且给定块检查以下收到的消息。

如果传入队列中没有消息,该方法将阻塞,直到新消息到达。

如果块被 break/return/exception/throw 转义,则消息将从传入队列中删除,就好像已返回真值一样。

r = Ractor.new do
  val = Ractor.receive_if{|msg| msg.is_a?(Array)}
  puts "Received successfully: #{val}"
end

r.send(1)
r.send('test')
wait
puts "2 non-matching sent, nothing received"
r.send([1, 2, 3])
wait

打印

2 non-matching sent, nothing received
Received successfully: [1, 2, 3]

请注意,您不能在给定块中递归调用 receive/receive_if。这意味着您不应该在块中执行任何任务。

Ractor.current << true
Ractor.receive_if{|msg| Ractor.receive}
#=> `receive': can not call receive/receive_if recursively (Ractor::Error)

相关用法


注:本文由纯净天空筛选整理自ruby-lang.org大神的英文原创作品 Ractor.receive_if。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。