Ractor サンプル https://www.ruby-lang.org/ja/news/2020/12/08/ruby-3-0-0-preview2-released/ require 'prime' # n.prime? with sent integers in r1, r2 run in parallel r1, r2 = *(1..2).map do Ractor.new do n = Ractor.receive n.prime? end end # send parameters r1.send 2**61 - 1 r2.send 2**61 + 15 # wait for the results of expr1, expr2 p r1.take #=> true p r2.take #=> true
Ractor 実行結果 実経過時間がRactorを使うことで1/2ほどになっている $ ruby -W0 prime_benchmark.rb user system total real normal 10.827434 0.001394 10.828828 ( 10.828979) Ractor 11.186445 0.000000 11.186445 ( 5.838678)
なぜRactorが遅かったのか Each Ractor has 1 or more Threads. ● 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). ● The overhead of creating a Ractor is similar to overhead of one Thread creation. Rubyドキュメントより https://github.com/ruby/ruby/blob/master/doc/ractor.md ● Ractor の生成コストが高いために遅くなった? ● 計算自体が CPU をフルに使うようなのではないため、利用 Ractor を使い切れ ていない? ● 実はパラレルには実行できないので遅い? ● GVLの制限が外れてるわけではない?