1 # Ractor - Ruby's Actor-like concurrent abstraction
3 Ractor is designed to provide a parallel execution feature of Ruby without thread-safety concerns.
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.
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.
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
79 * `Ractor.new{ expr }` generates another Ractor.
82 # Ractor.new with a block creates new Ractor
84 # This block will be run in parallel with other ractors
87 # You can name a Ractor with `name:` argument.
88 r = Ractor.new name: 'test-name' do
91 # and Ractor#name returns its name.
92 r.name #=> 'test-name'
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.
106 a #=> ArgumentError because this block accesses `a`.
113 * The `self` of the given block is the `Ractor` object itself.
117 p self.class #=> Ractor
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).
126 r = Ractor.new 'ok' do |msg|
133 # almost similar to the last example
142 ### An execution result of given block
144 Return value of the given block becomes an outgoing message (see below for details).
154 # almost similar to the last example
161 Error in the given block will be propagated to the receiver of an outgoing message.
165 raise 'ok' # exception will be transferred to the receiver
170 rescue Ractor::RemoteError => e
171 e.cause.class #=> RuntimeError
172 e.cause.message #=> 'ok'
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))
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.
217 +-------------------------------------------+
218 | incoming outgoing |
220 r.send(obj) ->*->[incoming queue] Ractor.yield(obj) ->*-> r.take
224 +-------------------------------------------+
227 Connection example: r2.send obj on r1ćRactor.receive on r2
233 Connection example: Ractor.yield(obj) on r1, r1.take on r2
238 Connection example: Ractor.yield(obj) on r1 and r2,
239 and waiting for both simultaneously by Ractor.select(r1, r2)
244 +----> Ractor.select(r1, r2)
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.
264 * main |------> * r *---+
267 +-------------------+
270 And this code can be simplified by using an argument for `Ractor.new`.
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.
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`.
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.
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`):
312 r1 = Ractor.new{'r1'}
314 r, obj = Ractor.select(r1)
315 r == r1 and obj == 'r1' #=> true
318 Wait for two ractors:
321 r1 = Ractor.new{'r1'}
322 r2 = Ractor.new{'r2'}
326 # Wait for r1 or r2's Ractor.yield
327 r, obj = Ractor.select(*rs)
331 # Second try (rs only contain not-closed ractors)
332 r, obj = Ractor.select(*rs)
335 as.sort == ['r1', 'r2'] #=> true
343 Ractor.yield Ractor.receive
348 rs = RN.times.map{|i|
349 Ractor.new pipe, i do |pipe, i|
358 r, n = Ractor.select(*rs)
361 }.sort #=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
364 Multiple Ractors can send to one Ractor.
367 # Create 10 ractors and they send objects to pipe ractor.
368 # pipe ractor yield received objects
372 Ractor.yield Ractor.receive
377 rs = RN.times.map{|i|
378 Ractor.new pipe, i do |pipe, i|
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):
410 r.take # success (will return 'finish')
412 o = r.take # try to take from closed Ractor
413 rescue Ractor::ClosedError
420 Example (try to send to closed (terminated) Ractor):
426 r.take # wait terminate
430 rescue Ractor::ClosedError
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.
445 r = Ractor.new obj do |msg|
446 # return received msg's object_id
450 obj.object_id == r.take #=> false
453 Some objects are not supported to copy the value, and raise an exception.
458 Ractor.new obj do |msg|
461 rescue TypeError => e
462 e.message #=> #<TypeError: allocator undefined for Thread>
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.
474 # move with Ractor#send
481 r.send str, move: true
482 modified = r.take #=> 'hello world'
484 # str is moved, and accessing str from this Ractor is prohibited
487 # Error because it touches moved str.
488 str << ' exception' # raise Ractor::MovedError
489 rescue Ractor::MovedError
490 modified #=> 'hello world'
497 # move with Ractor.yield
500 Ractor.yield obj, move: true
501 obj << 'world' # raise Ractor::MovedError
507 rescue Ractor::RemoteError
512 Some objects are not supported to move, and an exception will be raised.
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.
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)
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).
549 Only the main Ractor (a Ractor created at starting of interpreter) can access global variables.
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.
582 Otherwise, only the main Ractor can access instance variables of shareable objects.
586 @iv = [] # unshareable object
593 rescue Ractor::IsolationError
595 #=> "can not get unshareable values from instance variables of classes/modules from non-main Ractors"
600 rescue Ractor::IsolationError
602 #=> "can not set instance variables of classes/modules by non-main Ractors"
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)
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.
629 Only the main Ractor can access class variables.
646 e.class #=> Ractor::IsolationError
652 Only the main Ractor can read constants which refer to the unshareable object.
664 e.class #=> Ractor::IsolationError
668 Only the main Ractor can define constants which refer to the unshareable object.
679 e.class #=> Ractor::IsolationError
683 To make multi-ractor supported library, the constants should only refer shareable objects.
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.
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.
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`
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.
725 ### Traditional Ring example in Actor-model
737 r = Ractor.new r do |next_r|
738 next_r << Ractor.receive
759 rs = (1..RN).map do |i|
766 r, v = Ractor.select(*rs)
779 Ractor.yield Ractor.receive
785 workers = (1..RN).map do
786 Ractor.new pipe do |pipe|
788 Ractor.yield [n, n.prime?]
798 _r, (n, b) = Ractor.select(*workers)
800 }.sort_by{|(n, b)| n}
806 # pipeline with yield/take
811 r2 = Ractor.new r1 do |r1|
815 r3 = Ractor.new r2 do |r2|
819 p r3.take #=> 'r1r2r3'
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'
838 p Ractor.receive #=> "r0r1r2r3"
848 r = Ractor.new r, i do |r, i|
849 r.send Ractor.receive + "r#{i}"
854 p Ractor.receive #=> "r0r10r9r8r7r6r5r4r3r2r1"
858 # ring example with an error
862 r = Ractor.new r, i do |r, i|
872 p Ractor.receive #=> "r0r10r9r8r7r6r5r4r3r2r1"
874 p Ractor.select(*rs, Ractor.current) #=> [:receive, "r0r10r9r8r7r6r5r4r3r2r1"]
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)
892 # resend non-error message
896 r = Ractor.new r, i do |r, i|
906 p Ractor.receive #=> "r0r10r9r8r7r6r5r4r3r2r1"
908 p Ractor.select(*rs, Ractor.current)
909 [:receive, "r0r10r9r8r7r6r5r4r3r2r1"]
913 p Ractor.select(*rs, Ractor.current)
914 rescue Ractor::RemoteError
919 #=> <internal:ractor>:100:in `send': The incoming-port is already closed (Ractor::ClosedError)
920 # because r == r[-1] is terminated.
924 # ring example with supervisor and re-start
927 Ractor.new r, i do |r, i|
938 r = make_ractor(r, i)
941 msg = 'e0' # error causing message
944 p Ractor.select(*rs, Ractor.current)
945 rescue Ractor::RemoteError
946 r = rs[-1] = make_ractor(rs[-2], rs.size-1)
951 #=> [:receive, "x0r9r9r8r7r6r5r4r3r2r1"]