本文簡要介紹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 Ractor.receive用法及代碼示例
- 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_if。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。