From a9a7f4d8b8ec30abc7a47ce700edc7209ae12279 Mon Sep 17 00:00:00 2001 From: Koichi Sasada Date: Tue, 8 Dec 2020 14:04:18 +0900 Subject: Ractor#receive_if to receive only matched messages Instead of Ractor.receive, Ractor.receive_if can provide a pattern by a block and you can choose the receiving message. [Feature #17378] --- ractor.rb | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) (limited to 'ractor.rb') diff --git a/ractor.rb b/ractor.rb index c3a8f27532..b5b2677a2b 100644 --- a/ractor.rb +++ b/ractor.rb @@ -102,6 +102,47 @@ class Ractor end alias recv receive + # Receive only a specific message. + # + # Instead of Ractor.receive, Ractor.receive_if can provide a pattern + # by a block and you can choose the receiving message. + # + # # Example: + # r = Ractor.new do + # p Ractor.receive_if{|msg| /foo/ =~ msg} #=> "foo3" + # p Ractor.receive_if{|msg| /bar/ =~ msg} #=> "bar1" + # p Ractor.receive_if{|msg| /baz/ =~ msg} #=> "baz2" + # end + # r << "bar1" + # r << "baz2" + # r << "foo3" + # r.take + # + # If the block returns truthy, the message will be removed from incoming queue + # and return this method with the message. + # When the block is escaped by break/return/exception and so on, the message also + # removed from the incoming queue. + # Otherwise, the messsage is remained in the incoming queue and check next received + # message by the given block. + # + # If there is no messages in the incoming queue, wait until arrival of other messages. + # + # Note that you can not call receive/receive_if in the given block recursively. + # It means that you should not do any tasks in the block. + # + # # Example: + # Ractor.current << true + # Ractor.receive_if{|msg| Ractor.receive} + # #=> `receive': can not call receive/receive_if recursively (Ractor::Error) + # + def self.receive_if &b + Primitive.ractor_receive_if b + end + + def receive_if &b + Primitive.ractor_receive_if b + end + # Send a message to a Ractor's incoming queue. # # # Example: -- cgit v1.2.3