class Ractor::Selector
Ractor::Selector
provides a functionality to wait multiple Ractor
events. Ractor::Selector#wait
is more lightweight than Ractor.select()
because we don’t have to specify all target ractors for each wait time.
Ractor.select()
uses Ractor::Selector
internally to implement it.
Public Class Methods
Creates a selector object.
If a ractors parameter is given, it is same as the following code.
selector = Ractor::Selector.new ractors.each{|r| selector.add r}
# File ruby_3_3_0_preview3/ractor.rb, line 397 def self.new(*rs) selector = __builtin_cexpr! %q{ ractor_selector_create(self); } rs.each{|r| selector.add(r) } selector end
Public Instance Methods
Registers a ractor as a taking target by the selector.
# File ruby_3_3_0_preview3/ractor.rb, line 410 def add r __builtin_ractor_selector_add r end
Deregisters all ractors.
# File ruby_3_3_0_preview3/ractor.rb, line 427 def clear __builtin_ractor_selector_clear end
Returns true if the number of ractors in the waiting set at the current time is zero.
Note that even if #empty?
returns false, the subsequent #wait
may raise an exception because other ractors may close the target ractors.
# File ruby_3_3_0_preview3/ractor.rb, line 439 def empty? __builtin_ractor_selector_empty_p end
Deregisters a ractor as a taking target by the selector.
# File ruby_3_3_0_preview3/ractor.rb, line 419 def remove r __builtin_ractor_selector_remove r end
Waits Ractor
events. It is lighter than Ractor.select()
for many ractors.
The simplest form is waiting for taking a value from one of registerred ractors like that.
selector = Ractor::Selector.new(r1, r2, r3) r, v = selector.wait
On this case, when r1, r2 or r3 is ready to take (yielding a value), this method takes the value from the ready (yielded) ractor and returns [the yielded ractor, the taking value].
Note that if a take target ractor is closed, the ractor will be removed automatically.
If you also want to wait with receiving an object from other ractors, you can specify receive: true keyword like:
r, v = selector.wait receive: true
On this case, wait for taking from r1, r2 or r3 and waiting for receving a value from other ractors. If it successes the receiving, it returns an array object [:receive, the received value].
If you also want to wait with yielding a value, you can specify :yield_value like:
r, v = selector.wait yield_value: obj
On this case wait for taking from r1, r2, or r3 and waiting for taking yielding value (obj) by another ractor. If antoher ractor takes the value (obj), it returns an array object [:yield, nil].
You can specify a keyword parameter move: true
like Ractor.yield
(obj, move: true)
# File ruby_3_3_0_preview3/ractor.rb, line 481 def wait receive: false, yield_value: yield_unspecified = true, move: false __builtin_ractor_selector_wait receive, !yield_unspecified, yield_value, move end