[rubygems/rubygems] Use a constant empty tar header to avoid extra allocations
[ruby.git] / doc / ractor.md
blob7a69e839de7a27e7aa1fc8d8c61fc845bd3b5668
1 # Ractor - Ruby's Actor-like concurrent abstraction
3 Ractor is designed to provide a parallel execution feature of Ruby without thread-safety concerns.
5 ## Summary
7 ### Multiple Ractors in an interpreter process
9 You can make multiple Ractors and they run in parallel.
11 * `Ractor.new{ expr }` creates a new Ractor and `expr` is run in parallel on a parallel computer.
12 * Interpreter invokes with the first Ractor (called *main Ractor*).
13 * If main Ractor terminated, all Ractors receive terminate request like Threads (if main thread (first invoked Thread), Ruby interpreter sends all running threads to terminate execution).
14 * Each Ractor has 1 or more Threads.
15   * Threads in a Ractor shares a Ractor-wide global lock like GIL (GVL in MRI terminology), so they can't run in parallel (without releasing GVL explicitly in C-level). Threads in different ractors run in parallel.
16   * The overhead of creating a Ractor is similar to overhead of one Thread creation.
18 ### Limited sharing between multiple ractors
20 Ractors don't share everything, unlike threads.
22 * Most objects are *Unshareable objects*, so you don't need to care about thread-safety problems which are caused by sharing.
23 * Some objects are *Shareable objects*.
24   * Immutable objects: frozen objects which don't refer to unshareable-objects.
25     * `i = 123`: `i` is an immutable object.
26     * `s = "str".freeze`: `s` is an immutable object.
27     * `a = [1, [2], 3].freeze`: `a` is not an immutable object because `a` refers unshareable-object `[2]` (which is not frozen).
28     * `h = {c: Object}.freeze`: `h` is an immutable object because `h` refers Symbol `:c` and shareable `Object` class object which is not frozen.
29   * Class/Module objects
30   * Special shareable objects
31     * Ractor object itself.
32     * And more...
34 ### Two-types communication between Ractors
36 Ractors communicate with each other and synchronize the execution by message exchanging between Ractors. There are two message exchange protocols: push type (message passing) and pull type.
38 * Push type message passing: `Ractor#send(obj)` and `Ractor.receive()` pair.
39   * Sender ractor passes the `obj` to the ractor `r` by `r.send(obj)` and receiver ractor receives the message with `Ractor.receive`.
40   * Sender knows the destination Ractor `r` and the receiver does not know the sender (accept all messages from any ractors).
41   * Receiver has infinite queue and sender enqueues the message. Sender doesn't block to put message into this queue.
42   * This type of message exchanging is employed by many other Actor-based languages.
43   * `Ractor.receive_if{ filter_expr }` is a variant of `Ractor.receive` to select a message.
44 * Pull type communication: `Ractor.yield(obj)` and `Ractor#take()` pair.
45   * Sender ractor declare to yield the `obj` by `Ractor.yield(obj)` and receiver Ractor take it with `r.take`.
46   * Sender doesn't know a destination Ractor and receiver knows the sender Ractor `r`.
47   * Sender or receiver will block if there is no other side.
49 ### Copy & Move semantics to send messages
51 To send unshareable objects as messages, objects are copied or moved.
53 * Copy: use deep-copy.
54 * Move: move membership.
55   * Sender can not access the moved object after moving the object.
56   * Guarantee that at least only 1 Ractor can access the object.
58 ### Thread-safety
60 Ractor helps to write a thread-safe concurrent program, but we can make thread-unsafe programs with Ractors.
62 * GOOD: Sharing limitation
63   * Most objects are unshareable, so we can't make data-racy and race-conditional programs.
64   * Shareable objects are protected by an interpreter or locking mechanism.
65 * BAD: Class/Module can violate this assumption
66   * To make it compatible with old behavior, classes and modules can introduce data-race and so on.
67   * Ruby programmers should take care if they modify class/module objects on multi Ractor programs.
68 * BAD: Ractor can't solve all thread-safety problems
69   * There are several blocking operations (waiting send, waiting yield and waiting take) so you can make a program which has dead-lock and live-lock issues.
70   * Some kind of shareable objects can introduce transactions (STM, for example). However, misusing transactions will generate inconsistent state.
72 Without Ractor, we need to trace all state-mutations to debug thread-safety issues.
73 With Ractor, you can concentrate on suspicious code which are shared with Ractors.
75 ## Creation and termination
77 ### `Ractor.new`
79 * `Ractor.new{ expr }` generates another Ractor.
81 ```ruby
82 # Ractor.new with a block creates new Ractor
83 r = Ractor.new do
84   # This block will be run in parallel with other ractors
85 end
87 # You can name a Ractor with `name:` argument.
88 r = Ractor.new name: 'test-name' do
89 end
91 # and Ractor#name returns its name.
92 r.name #=> 'test-name'
93 ```
95 ### Given block isolation
97 The Ractor executes given `expr` in a given block.
98 Given block will be isolated from outer scope by the `Proc#isolate` method (not exposed yet for Ruby users). To prevent sharing unshareable objects between ractors, block outer-variables, `self` and other information are isolated.
100 `Proc#isolate` is called at Ractor creation time (when `Ractor.new` is called). If given Proc object is not able to isolate because of outer variables and so on, an error will be raised.
102 ```ruby
103 begin
104   a = true
105   r = Ractor.new do
106     a #=> ArgumentError because this block accesses `a`.
107   end
108   r.take # see later
109 rescue ArgumentError
113 * The `self` of the given block is the `Ractor` object itself.
115 ```ruby
116 r = Ractor.new do
117   p self.class #=> Ractor
118   self.object_id
120 r.take == self.object_id #=> false
123 Passed arguments to `Ractor.new()` becomes block parameters for the given block. However, an interpreter does not pass the parameter object references, but send them as messages (see below for details).
125 ```ruby
126 r = Ractor.new 'ok' do |msg|
127   msg #=> 'ok'
129 r.take #=> 'ok'
132 ```ruby
133 # almost similar to the last example
134 r = Ractor.new do
135   msg = Ractor.receive
136   msg
138 r.send 'ok'
139 r.take #=> 'ok'
142 ### An execution result of given block
144 Return value of the given block becomes an outgoing message (see below for details).
146 ```ruby
147 r = Ractor.new do
148   'ok'
150 r.take #=> `ok`
153 ```ruby
154 # almost similar to the last example
155 r = Ractor.new do
156   Ractor.yield 'ok'
158 r.take #=> 'ok'
161 Error in the given block will be propagated to the receiver of an outgoing message.
163 ```ruby
164 r = Ractor.new do
165   raise 'ok' # exception will be transferred to the receiver
168 begin
169   r.take
170 rescue Ractor::RemoteError => e
171   e.cause.class   #=> RuntimeError
172   e.cause.message #=> 'ok'
173   e.ractor        #=> r
177 ## Communication between Ractors
179 Communication between Ractors is achieved by sending and receiving messages. There are two ways to communicate with each other.
181 * (1) Message sending/receiving
182   * (1-1) push type send/receive (sender knows receiver). Similar to the Actor model.
183   * (1-2) pull type yield/take (receiver knows sender).
184 * (2) Using shareable container objects
185   * Ractor::TVar gem ([ko1/ractor-tvar](https://github.com/ko1/ractor-tvar))
186   * more?
188 Users can control program execution timing with (1), but should not control with (2) (only manage as critical section).
190 For message sending and receiving, there are two types of APIs: push type and pull type.
192 * (1-1) send/receive (push type)
193   * `Ractor#send(obj)` (`Ractor#<<(obj)` is an alias) send a message to the Ractor's incoming port. Incoming port is connected to the infinite size incoming queue so `Ractor#send` will never block.
194   * `Ractor.receive` dequeue a message from its own incoming queue. If the incoming queue is empty, `Ractor.receive` calling will block.
195   * `Ractor.receive_if{|msg| filter_expr }` is variant of `Ractor.receive`. `receive_if` only receives a message which `filter_expr` is true (So `Ractor.receive` is the same as `Ractor.receive_if{ true }`.
196 * (1-2) yield/take (pull type)
197   * `Ractor.yield(obj)` send an message to a Ractor which are calling `Ractor#take` via outgoing port . If no Ractors are waiting for it, the `Ractor.yield(obj)` will block. If multiple Ractors are waiting for `Ractor.yield(obj)`, only one Ractor can receive the message.
198   * `Ractor#take` receives a message which is waiting by `Ractor.yield(obj)` method from the specified Ractor. If the Ractor does not call `Ractor.yield` yet, the `Ractor#take` call will block.
199 * `Ractor.select()` can wait for the success of `take`, `yield` and `receive`.
200 * You can close the incoming port or outgoing port.
201   * You can close then with `Ractor#close_incoming` and `Ractor#close_outgoing`.
202   * If the incoming port is closed for a Ractor, you can't `send` to the Ractor. If `Ractor.receive` is blocked for the closed incoming port, then it will raise an exception.
203   * If the outgoing port is closed for a Ractor, you can't call `Ractor#take` and `Ractor.yield` on the Ractor. If ractors are blocking by `Ractor#take` or `Ractor.yield`, closing outgoing port will raise an exception on these blocking ractors.
204   * When a Ractor is terminated, the Ractor's ports are closed.
205 * There are 3 ways to send an object as a message
206   * (1) Send a reference: Sending a shareable object, send only a reference to the object (fast)
207   * (2) Copy an object: Sending an unshareable object by copying an object deeply (slow). Note that you can not send an object which does not support deep copy. Some `T_DATA` objects (objects whose class is defined in a C extension, such as `StringIO`) are not supported.
208   * (3) Move an object: Sending an unshareable object reference with a membership. Sender Ractor can not access moved objects anymore (raise an exception) after moving it. Current implementation makes new object as a moved object for receiver Ractor and copies references of sending object to moved object. `T_DATA` objects are not supported.
209   * You can choose "Copy" and "Move" by the `move:` keyword, `Ractor#send(obj, move: true/false)` and `Ractor.yield(obj, move: true/false)` (default is `false` (COPY)).
211 ### Sending/Receiving ports
213 Each Ractor has _incoming-port_ and _outgoing-port_. Incoming-port is connected to the infinite sized incoming queue.
216                   Ractor r
217                  +-------------------------------------------+
218                  | incoming                         outgoing |
219                  | port                                 port |
220    r.send(obj) ->*->[incoming queue]     Ractor.yield(obj) ->*-> r.take
221                  |                |                          |
222                  |                v                          |
223                  |           Ractor.receive                  |
224                  +-------------------------------------------+
227 Connection example: r2.send obj on r1态Ractor.receive on r2
228   +----+     +----+
229   * r1 |---->* r2 *
230   +----+     +----+
233 Connection example: Ractor.yield(obj) on r1, r1.take on r2
234   +----+     +----+
235   * r1 *---->- r2 *
236   +----+     +----+
238 Connection example: Ractor.yield(obj) on r1 and r2,
239                     and waiting for both simultaneously by Ractor.select(r1, r2)
241   +----+
242   * r1 *------+
243   +----+      |
244               +----> Ractor.select(r1, r2)
245   +----+      |
246   * r2 *------|
247   +----+
250 ```ruby
251 r = Ractor.new do
252   msg = Ractor.receive # Receive from r's incoming queue
253   msg # send back msg as block return value
255 r.send 'ok' # Send 'ok' to r's incoming port -> incoming queue
256 r.take      # Receive from r's outgoing port
259 The last example shows the following ractor network.
263   +------+        +---+
264   * main |------> * r *---+
265   +------+        +---+   |
266       ^                   |
267       +-------------------+
270 And this code can be simplified by using an argument for `Ractor.new`.
272 ```ruby
273 # Actual argument 'ok' for `Ractor.new()` will be sent to created Ractor.
274 r = Ractor.new 'ok' do |msg|
275   # Values for formal parameters will be received from incoming queue.
276   # Similar to: msg = Ractor.receive
278   msg # Return value of the given block will be sent via outgoing port
281 # receive from the r's outgoing port.
282 r.take #=> `ok`
285 ### Return value of a block for `Ractor.new`
287 As already explained, the return value of `Ractor.new` (an evaluated value of `expr` in `Ractor.new{ expr }`) can be taken by `Ractor#take`.
289 ```ruby
290 Ractor.new{ 42 }.take #=> 42
293 When the block return value is available, the Ractor is dead so that no ractors except taken Ractor can touch the return value, so any values can be sent with this communication path without any modification.
295 ```ruby
296 r = Ractor.new do
297   a = "hello"
298   binding
301 r.take.eval("p a") #=> "hello" (other communication path can not send a Binding object directly)
304 ### Wait for multiple Ractors with `Ractor.select`
306 You can wait multiple Ractor's `yield` with `Ractor.select(*ractors)`.
307 The return value of `Ractor.select()` is `[r, msg]` where `r` is yielding Ractor and `msg` is yielded message.
309 Wait for a single ractor (same as `Ractor.take`):
311 ```ruby
312 r1 = Ractor.new{'r1'}
314 r, obj = Ractor.select(r1)
315 r == r1 and obj == 'r1' #=> true
318 Wait for two ractors:
320 ```ruby
321 r1 = Ractor.new{'r1'}
322 r2 = Ractor.new{'r2'}
323 rs = [r1, r2]
324 as = []
326 # Wait for r1 or r2's Ractor.yield
327 r, obj = Ractor.select(*rs)
328 rs.delete(r)
329 as << obj
331 # Second try (rs only contain not-closed ractors)
332 r, obj = Ractor.select(*rs)
333 rs.delete(r)
334 as << obj
335 as.sort == ['r1', 'r2'] #=> true
338 Complex example:
340 ```ruby
341 pipe = Ractor.new do
342   loop do
343     Ractor.yield Ractor.receive
344   end
347 RN = 10
348 rs = RN.times.map{|i|
349   Ractor.new pipe, i do |pipe, i|
350     msg = pipe.take
351     msg # ping-pong
352   end
354 RN.times{|i|
355   pipe << i
357 RN.times.map{
358   r, n = Ractor.select(*rs)
359   rs.delete r
360   n
361 }.sort #=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
364 Multiple Ractors can send to one Ractor.
366 ```ruby
367 # Create 10 ractors and they send objects to pipe ractor.
368 # pipe ractor yield received objects
370 pipe = Ractor.new do
371   loop do
372     Ractor.yield Ractor.receive
373   end
376 RN = 10
377 rs = RN.times.map{|i|
378   Ractor.new pipe, i do |pipe, i|
379     pipe << i
380   end
383 RN.times.map{
384   pipe.take
385 }.sort #=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
388 TODO: Current `Ractor.select()` has the same issue of `select(2)`, so this interface should be refined.
390 TODO: `select` syntax of go-language uses round-robin technique to make fair scheduling. Now `Ractor.select()` doesn't use it.
392 ### Closing Ractor's ports
394 * `Ractor#close_incoming/outgoing` close incoming/outgoing ports (similar to `Queue#close`).
395 * `Ractor#close_incoming`
396   * `r.send(obj)` where `r`'s incoming port is closed, will raise an exception.
397   * When the incoming queue is empty and incoming port is closed, `Ractor.receive` raises an exception. If the incoming queue is not empty, it dequeues an object without exceptions.
398 * `Ractor#close_outgoing`
399   * `Ractor.yield` on a Ractor which closed the outgoing port, it will raise an exception.
400   * `Ractor#take` for a Ractor which closed the outgoing port, it will raise an exception. If `Ractor#take` is blocking, it will raise an exception.
401 * When a Ractor terminates, the ports are closed automatically.
402   * Return value of the Ractor's block will be yielded as `Ractor.yield(ret_val)`, even if the implementation terminates the based native thread.
404 Example (try to take from closed Ractor):
406 ```ruby
407 r = Ractor.new do
408   'finish'
410 r.take # success (will return 'finish')
411 begin
412   o = r.take # try to take from closed Ractor
413 rescue Ractor::ClosedError
414   'ok'
415 else
416   "ng: #{o}"
420 Example (try to send to closed (terminated) Ractor):
422 ```ruby
423 r = Ractor.new do
426 r.take # wait terminate
428 begin
429   r.send(1)
430 rescue Ractor::ClosedError
431   'ok'
432 else
433   'ng'
437 When multiple Ractors are waiting for `Ractor.yield()`, `Ractor#close_outgoing` will cancel all blocking by raising an exception (`ClosedError`).
439 ### Send a message by copying
441 `Ractor#send(obj)` or `Ractor.yield(obj)` copy `obj` deeply if `obj` is an unshareable object.
443 ```ruby
444 obj = 'str'.dup
445 r = Ractor.new obj do |msg|
446   # return received msg's object_id
447   msg.object_id
450 obj.object_id == r.take #=> false
453 Some objects are not supported to copy the value, and raise an exception.
455 ```ruby
456 obj = Thread.new{}
457 begin
458   Ractor.new obj do |msg|
459     msg
460   end
461 rescue TypeError => e
462   e.message #=> #<TypeError: allocator undefined for Thread>
463 else
464   'ng' # unreachable here
468 ### Send a message by moving
470 `Ractor#send(obj, move: true)` or `Ractor.yield(obj, move: true)` move `obj` to the destination Ractor.
471 If the source Ractor touches the moved object (for example, call the method like `obj.foo()`), it will be an error.
473 ```ruby
474 # move with Ractor#send
475 r = Ractor.new do
476   obj = Ractor.receive
477   obj << ' world'
480 str = 'hello'
481 r.send str, move: true
482 modified = r.take #=> 'hello world'
484 # str is moved, and accessing str from this Ractor is prohibited
486 begin
487   # Error because it touches moved str.
488   str << ' exception' # raise Ractor::MovedError
489 rescue Ractor::MovedError
490   modified #=> 'hello world'
491 else
492   raise 'unreachable'
496 ```ruby
497 # move with Ractor.yield
498 r = Ractor.new do
499   obj = 'hello'
500   Ractor.yield obj, move: true
501   obj << 'world'  # raise Ractor::MovedError
504 str = r.take
505 begin
506   r.take
507 rescue Ractor::RemoteError
508   p str #=> "hello"
512 Some objects are not supported to move, and an exception will be raised.
514 ```ruby
515 r = Ractor.new do
516   Ractor.receive
519 r.send(Thread.new{}, move: true) #=> allocator undefined for Thread (TypeError)
522 To achieve the access prohibition for moved objects, _class replacement_ technique is used to implement it.
524 ### Shareable objects
526 The following objects are shareable.
528 * Immutable objects
529   * Small integers, some symbols, `true`, `false`, `nil` (a.k.a. `SPECIAL_CONST_P()` objects in internal)
530   * Frozen native objects
531     * Numeric objects: `Float`, `Complex`, `Rational`, big integers (`T_BIGNUM` in internal)
532     * All Symbols.
533   * Frozen `String` and `Regexp` objects (their instance variables should refer only shareable objects)
534 * Class, Module objects (`T_CLASS`, `T_MODULE` and `T_ICLASS` in internal)
535 * `Ractor` and other special objects which care about synchronization.
537 Implementation: Now shareable objects (`RVALUE`) have `FL_SHAREABLE` flag. This flag can be added lazily.
539 To make shareable objects, `Ractor.make_shareable(obj)` method is provided. In this case, try to make sharaeble by freezing `obj` and recursively traversable objects. This method accepts `copy:` keyword (default value is false).`Ractor.make_shareable(obj, copy: true)` tries to make a deep copy of `obj` and make the copied object shareable.
541 ## Language changes to isolate unshareable objects between Ractors
543 To isolate unshareable objects between Ractors, we introduced additional language semantics on multi-Ractor Ruby programs.
545 Note that without using Ractors, these additional semantics is not needed (100% compatible with Ruby 2).
547 ### Global variables
549 Only the main Ractor (a Ractor created at starting of interpreter) can access global variables.
551 ```ruby
552 $gv = 1
553 r = Ractor.new do
554   $gv
557 begin
558   r.take
559 rescue Ractor::RemoteError => e
560   e.cause.message #=> 'can not access global variables from non-main Ractors'
564 Note that some special global variables are ractor-local, like `$stdin`, `$stdout`, `$stderr`. See [[Bug #17268]](https://bugs.ruby-lang.org/issues/17268) for more details.
566 ### Instance variables of shareable objects
568 Instance variables of classes/modules can be get from non-main Ractors if the referring values are shareable objects.
570 ```ruby
571 class C
572   @iv = 1
575 p Ractor.new do
576   class C
577      @iv
578   end
579 end.take #=> 1
582 Otherwise, only the main Ractor can access instance variables of shareable objects.
584 ```ruby
585 class C
586   @iv = [] # unshareable object
589 Ractor.new do
590   class C
591     begin
592       p @iv
593     rescue Ractor::IsolationError
594       p $!.message
595       #=> "can not get unshareable values from instance variables of classes/modules from non-main Ractors"
596     end
598     begin
599       @iv = 42
600     rescue Ractor::IsolationError
601       p $!.message
602       #=> "can not set instance variables of classes/modules by non-main Ractors"
603     end
604   end
605 end.take
610 ```ruby
611 shared = Ractor.new{}
612 shared.instance_variable_set(:@iv, 'str')
614 r = Ractor.new shared do |shared|
615   p shared.instance_variable_get(:@iv)
618 begin
619   r.take
620 rescue Ractor::RemoteError => e
621   e.cause.message #=> can not access instance variables of shareable objects from non-main Ractors (Ractor::IsolationError)
625 Note that instance variables for class/module objects are also prohibited on Ractors.
627 ### Class variables
629 Only the main Ractor can access class variables.
631 ```ruby
632 class C
633   @@cv = 'str'
636 r = Ractor.new do
637   class C
638     p @@cv
639   end
643 begin
644   r.take
645 rescue => e
646   e.class #=> Ractor::IsolationError
650 ### Constants
652 Only the main Ractor can read constants which refer to the unshareable object.
654 ```ruby
655 class C
656   CONST = 'str'
658 r = Ractor.new do
659   C::CONST
661 begin
662   r.take
663 rescue => e
664   e.class #=> Ractor::IsolationError
668 Only the main Ractor can define constants which refer to the unshareable object.
670 ```ruby
671 class C
673 r = Ractor.new do
674   C::CONST = 'str'
676 begin
677   r.take
678 rescue => e
679   e.class #=> Ractor::IsolationError
683 To make multi-ractor supported library, the constants should only refer shareable objects.
685 ```ruby
686 TABLE = {a: 'ko1', b: 'ko2', c: 'ko3'}
689 In this case, `TABLE` references an unshareable Hash object. So that other ractors can not refer `TABLE` constant. To make it shareable, we can use `Ractor.make_shareable()` like that.
691 ```ruby
692 TABLE = Ractor.make_shareable( {a: 'ko1', b: 'ko2', c: 'ko3'} )
695 To make it easy, Ruby 3.0 introduced new `shareable_constant_value` Directive.
697 ```ruby
698 # shareable_constant_value: literal
700 TABLE = {a: 'ko1', b: 'ko2', c: 'ko3'}
701 #=> Same as: TABLE = Ractor.make_shareable( {a: 'ko1', b: 'ko2', c: 'ko3'} )
704 `shareable_constant_value` directive accepts the following modes (descriptions use the example: `CONST = expr`):
706 * none: Do nothing. Same as: `CONST = expr`
707 * literal:
708   * if `expr` consists of literals, replaced to `CONST = Ractor.make_shareable(expr)`.
709   * otherwise: replaced to `CONST = expr.tap{|o| raise unless Ractor.shareable?(o)}`.
710 * experimental_everything: replaced to `CONST = Ractor.make_shareable(expr)`.
711 * experimental_copy: replaced to `CONST = Ractor.make_shareable(expr, copy: true)`.
713 Except the `none` mode (default), it is guaranteed that the assigned constants refer to only shareable objects.
715 See [doc/syntax/comments.rdoc](syntax/comments.rdoc) for more details.
717 ## Implementation note
719 * Each Ractor has its own thread, it means each Ractor has at least 1 native thread.
720 * Each Ractor has its own ID (`rb_ractor_t::pub::id`).
721   * On debug mode, all unshareable objects are labeled with current Ractor's id, and it is checked to detect unshareable object leak (access an object from different Ractor) in VM.
723 ## Examples
725 ### Traditional Ring example in Actor-model
727 ```ruby
728 RN = 1_000
729 CR = Ractor.current
731 r = Ractor.new do
732   p Ractor.receive
733   CR << :fin
736 RN.times{
737   r = Ractor.new r do |next_r|
738     next_r << Ractor.receive
739   end
742 p :setup_ok
743 r << 1
744 p Ractor.receive
747 ### Fork-join
749 ```ruby
750 def fib n
751   if n < 2
752     1
753   else
754     fib(n-2) + fib(n-1)
755   end
758 RN = 10
759 rs = (1..RN).map do |i|
760   Ractor.new i do |i|
761     [i, fib(i)]
762   end
765 until rs.empty?
766   r, v = Ractor.select(*rs)
767   rs.delete r
768   p answer: v
772 ### Worker pool
774 ```ruby
775 require 'prime'
777 pipe = Ractor.new do
778   loop do
779     Ractor.yield Ractor.receive
780   end
783 N = 1000
784 RN = 10
785 workers = (1..RN).map do
786   Ractor.new pipe do |pipe|
787     while n = pipe.take
788       Ractor.yield [n, n.prime?]
789     end
790   end
793 (1..N).each{|i|
794   pipe << i
797 pp (1..N).map{
798   _r, (n, b) = Ractor.select(*workers)
799   [n, b]
800 }.sort_by{|(n, b)| n}
803 ### Pipeline
805 ```ruby
806 # pipeline with yield/take
807 r1 = Ractor.new do
808   'r1'
811 r2 = Ractor.new r1 do |r1|
812   r1.take + 'r2'
815 r3 = Ractor.new r2 do |r2|
816   r2.take + 'r3'
819 p r3.take #=> 'r1r2r3'
822 ```ruby
823 # pipeline with send/receive
825 r3 = Ractor.new Ractor.current do |cr|
826   cr.send Ractor.receive + 'r3'
829 r2 = Ractor.new r3 do |r3|
830   r3.send Ractor.receive + 'r2'
833 r1 = Ractor.new r2 do |r2|
834   r2.send Ractor.receive + 'r1'
837 r1 << 'r0'
838 p Ractor.receive #=> "r0r1r2r3"
841 ### Supervise
843 ```ruby
844 # ring example again
846 r = Ractor.current
847 (1..10).map{|i|
848   r = Ractor.new r, i do |r, i|
849     r.send Ractor.receive + "r#{i}"
850   end
853 r.send "r0"
854 p Ractor.receive #=> "r0r10r9r8r7r6r5r4r3r2r1"
857 ```ruby
858 # ring example with an error
860 r = Ractor.current
861 rs = (1..10).map{|i|
862   r = Ractor.new r, i do |r, i|
863     loop do
864       msg = Ractor.receive
865       raise if /e/ =~ msg
866       r.send msg + "r#{i}"
867     end
868   end
871 r.send "r0"
872 p Ractor.receive #=> "r0r10r9r8r7r6r5r4r3r2r1"
873 r.send "r0"
874 p Ractor.select(*rs, Ractor.current) #=> [:receive, "r0r10r9r8r7r6r5r4r3r2r1"]
875 r.send "e0"
876 p Ractor.select(*rs, Ractor.current)
878 #<Thread:0x000056262de28bd8 run> terminated with exception (report_on_exception is true):
879 Traceback (most recent call last):
880         2: from /home/ko1/src/ruby/trunk/test.rb:7:in `block (2 levels) in <main>'
881         1: from /home/ko1/src/ruby/trunk/test.rb:7:in `loop'
882 /home/ko1/src/ruby/trunk/test.rb:9:in `block (3 levels) in <main>': unhandled exception
883 Traceback (most recent call last):
884         2: from /home/ko1/src/ruby/trunk/test.rb:7:in `block (2 levels) in <main>'
885         1: from /home/ko1/src/ruby/trunk/test.rb:7:in `loop'
886 /home/ko1/src/ruby/trunk/test.rb:9:in `block (3 levels) in <main>': unhandled exception
887         1: from /home/ko1/src/ruby/trunk/test.rb:21:in `<main>'
888 <internal:ractor>:69:in `select': thrown by remote Ractor. (Ractor::RemoteError)
891 ```ruby
892 # resend non-error message
894 r = Ractor.current
895 rs = (1..10).map{|i|
896   r = Ractor.new r, i do |r, i|
897     loop do
898       msg = Ractor.receive
899       raise if /e/ =~ msg
900       r.send msg + "r#{i}"
901     end
902   end
905 r.send "r0"
906 p Ractor.receive #=> "r0r10r9r8r7r6r5r4r3r2r1"
907 r.send "r0"
908 p Ractor.select(*rs, Ractor.current)
909 [:receive, "r0r10r9r8r7r6r5r4r3r2r1"]
910 msg = 'e0'
911 begin
912   r.send msg
913   p Ractor.select(*rs, Ractor.current)
914 rescue Ractor::RemoteError
915   msg = 'r0'
916   retry
919 #=> <internal:ractor>:100:in `send': The incoming-port is already closed (Ractor::ClosedError)
920 # because r == r[-1] is terminated.
923 ```ruby
924 # ring example with supervisor and re-start
926 def make_ractor r, i
927   Ractor.new r, i do |r, i|
928     loop do
929       msg = Ractor.receive
930       raise if /e/ =~ msg
931       r.send msg + "r#{i}"
932     end
933   end
936 r = Ractor.current
937 rs = (1..10).map{|i|
938   r = make_ractor(r, i)
941 msg = 'e0' # error causing message
942 begin
943   r.send msg
944   p Ractor.select(*rs, Ractor.current)
945 rescue Ractor::RemoteError
946   r = rs[-1] = make_ractor(rs[-2], rs.size-1)
947   msg = 'x0'
948   retry
951 #=> [:receive, "x0r9r9r8r7r6r5r4r3r2r1"]