Ruby Ractors: isolation, message cost and where they scale
Ruby threads take turns under one lock, the GVL, so a CPU-bound Ruby program uses one core however many threads it starts. Ractors (Ruby 3.0+) are the way to run Ruby code on several cores inside one process: each Ractor has its own lock, and in exchange Ractors share almost nothing. This article covers what may cross between them, the Ruby 4.0 API, and six workloads measured on 1, 2, 4 and 8 pinned cores against threads and fork. In short, integer and float work scale. Code that allocates objects at a high rate does not: 8 Ractors building Strings finish fewer tasks per second than 1.
At a glance
| Threads | Ractors | fork (Puma cluster, Sidekiq swarm) | |
|---|---|---|---|
| Ruby code on several cores | no: one GVL per process | yes: one GVL per Ractor | yes: one process per worker |
| Shared memory | everything | only shareable (deep-frozen) objects | copy-on-write after the fork; nothing shared after a write |
| Passing data | a reference | deep copy, move: true or a shareable object | pipes, sockets, Redis: serialised |
8 workers, integer work (fib) | 1.0× | 4.8× | 7.8× |
| 8 workers, String allocation | 0.9× | 0.9× | 7.9× |
8 workers, JSON.parse | 0.9× | 1.2× | 7.6× |
| Start one, run an empty block, wait | 33 µs | 21 µs | 832 µs |
| Gems that work | all | only Ractor-safe ones | all |
| Status in Ruby 4.0 | stable | experimental (prints a warning) | stable |
Speed-ups are tasks per second against one thread of the same workload, 8 Cortex-A725 cores, Ruby 4.0.9 with YJIT; median of 9 trials (see Method). 28 whole programs measured the same way: Ractors vs threads vs fork: 28 Ruby benchmarks.
What a Ractor is
A Ractor is an actor with its own heap of objects and its own GVL. Threads inside one Ractor still take turns; two Ractors run Ruby code at the same time on two cores. The price is isolation: a Ractor may not touch another Ractor’s mutable objects, so most of what a Ruby program shares by accident (constants holding a Hash, $globals, class-level caches) is off limits outside the main Ractor.
An object is shareable when every Ractor may read it at the same time:
| Shareable | Not shareable |
|---|---|
nil, true, false, Integer, Float, Symbol | a String, Array or Hash that is not frozen |
| a frozen String, or a frozen Array/Hash whose elements are all shareable | a frozen Array holding an unfrozen String ([+"x"].freeze) |
classes and modules, Ractor objects, Ractor::Port | a Proc that refers to outer local variables |
anything passed through Ractor.make_shareable (deep-freezes in place) | an object with unshareable instance variables |
Everything else crosses between Ractors in one of three ways:
send / << | What happens | Cost (measured below) |
|---|---|---|
r.send(obj) | deep copy: the receiver gets new objects | grows with the object graph |
r.send(obj, move: true) | the receiver takes the objects; any call on the sender’s reference, even .class, raises Ractor::MovedError | grows with the object graph; 41–54 % of a copy from 100 KB up |
r.send(shareable) | the same object, no copy | flat; make_shareable itself walks the graph once |
What a non-main Ractor gets when it reaches for shared state, in Ruby 4.0.9:
Code inside Ractor.new { … } | Result |
|---|---|
CONFIG["retries"] with CONFIG = { "retries" => 3 } | Ractor::IsolationError: can not access non-shareable objects in constant Object::CONFIG by non-main Ractor. |
the same with CONFIG = Ractor.make_shareable({ … }) | works |
$counter | Ractor::IsolationError: can not access global variable $counter from non-main Ractor |
Cache.store returning a class-level @store = {} | Ractor::IsolationError: can not get unshareable values from instance variables of classes/modules from non-main Ractors (@store from Cache) |
x where x is a local of the creating method | ArgumentError at Ractor.new: can not isolate a Proc because it accesses outer variables (x). |
obj.size after r.send(obj, move: true) | Ractor::MovedError: can not send any methods to a moved object |
require "json" | works: the require runs on the main Ractor |
calling a method made with define_method { … } in the main Ractor | RuntimeError: defined with an un-shareable Proc in a different Ractor |
The error inside the Ractor reaches the caller of #value or #join as Ractor::RemoteError, with the original exception in #cause.
For constants there is a file-level shortcut: the magic comment # shareable_constant_value: literal runs Ractor.make_shareable on every constant in that file that is assigned a literal, and raises at assignment when any other constant value is not shareable; experimental_everything wraps every constant in Ractor.make_shareable.
Ruby 4.0: ports instead of take and yield
Ruby 3.0–3.4 moved values with Ractor.yield and Ractor#take. Ruby 4.0 removed both, together with close_incoming/close_outgoing, and added Ractor::Port: a mailbox that any Ractor may send to and only the Ractor that created it may receive from. Each Ractor still has a default port, which is what Ractor#send and Ractor.receive use.
| Task | Ruby 3.4 | Ruby 4.0 |
|---|---|---|
| wait for the block’s result | r.take | r.value |
| wait for it to finish | r.take | r.join |
| a Ractor reports back to its creator | Ractor.yield x / r.take | port << x / port.receive |
| be told when a Ractor dies | — | r.monitor(port); the port receives :exited or :aborted |
| a reply channel per request | a new Ractor as a pipe | Ractor::Port.new sent along with the request |
| receive on a port from another Ractor | — | Ractor::Error: only allowed from the creator Ractor of this port |
# Ruby 4.0: N workers, one result port owned by the main Ractor
results = Ractor::Port.new
workers = 4.times.map do |i|
Ractor.new(results, i) do |out, i|
while (job = Ractor.receive) # jobs arrive on the worker's default port
out << [i, job, job * job] # the main Ractor is the only one that may receive from `out`
end
end
end
10.times { |j| workers[j % 4].send(j) }
p 10.times.map { results.receive }
workers.each { _1.send(nil) }.each(&:join)
Ruby 4.0 still prints warning: Ractor API is experimental and may change in future versions of Ruby. the first time a program calls Ractor.new.
Measured: six workloads on 1–8 cores
Each workload is a fixed number of identical tasks, split across W workers on exactly W cores: W threads fed by a Queue, W Ractors fed by send and answering on one Ractor::Port, or W forked children fed over pipes (the shape of a Puma cluster). Ruby 4.0.9 with YJIT, Cortex-A725 cores at 2.8 GHz. Checksums are identical across all models and worker counts.
| Workload | One task |
|---|---|
| Integer (fib) | fib(22): method calls and Integer arithmetic, no allocation |
| Float loop | 20,000 Float multiply-adds (Floats are immediates on 64-bit, no allocation) |
| String alloc | 2,000 interpolated Strings in an Array, then their byte sizes summed |
| Hash alloc | 500 Hashes { id:, name:, tags: [..] }, then summed |
| JSON.parse | parse a 15 KB JSON document (200 records) and sum fields |
| String#to_sym | 2,000 lookups of Symbols that already exist |
| Workload | 1 thread | 8 threads | 1 Ractor | 2 Ractors | 4 Ractors | 8 Ractors | 8 × fork |
|---|---|---|---|---|---|---|---|
| Integer (fib) | 2,340 | 1.0× | 0.9× | 1.8× | 3.6× | 4.8× | 7.8× |
| Float loop | 1,270 | 1.0× | 1.0× | 1.9× | 3.9× | 5.8× | 7.9× |
| String alloc | 1,541 | 0.9× | 1.0× | 1.4× | 1.4× | 0.9× | 7.9× |
| Hash alloc | 4,995 | 1.0× | 1.0× | 1.5× | 1.6× | 1.0× | 7.7× |
| JSON.parse | 6,550 | 0.9× | 1.0× | 1.5× | 1.9× | 1.2× | 7.6× |
| String#to_sym | 5,289 | 1.1× | 1.2× | 2.2× | 4.1× | 6.4× | 7.8× |
The 1-thread column is tasks per second; the rest are speed-ups over it. Median of 9 trials: 3 passes of 3 interleaved trials, each cell re-run whenever anything else on the machine was busy. Within a trial, 8 Ractors over 1 thread ranged 4.82–4.97× on fib, 0.79–0.95× on Strings, 0.98–1.05× on Hashes, 1.12–1.20× on JSON.parse and 5.63–6.85× on Symbols. The first version of this table (26 November) ran next to other jobs on the same machine and put Strings at 0.7×; it is replaced.
- Threads stay at 1×, as the GVL predicts, and lose 13 % on String allocation at 8.
- Ractors scale work that does not allocate: 4.8× on
fib, 5.8× on Floats, 6.4× on Symbol lookups (the symbol table did not serialise them). - Ractors do not scale work that allocates. String building peaks at 1.4× with 2–4 Ractors and falls to 0.9× at 8, slower than one Ractor. Hashes and
JSON.parsepeak at 1.6–1.9× with 4 and fall back to 1.0–1.2×. (The Ruby vs Rust runs measured 1.5× for Ractors on a bigger JSON task — a 145 KB parse, reshape and generate on x86 — against 6.5× forfork: the same gap.) forkscales everything: 7.6–7.9× on 8 cores, because each process has its own heap and its own garbage collector.
Why allocation stops Ractors
The heap and the garbage collector are shared by all Ractors. Two places in Ruby 4.0.9’s collector (gc/default/default.c) make Ractors wait for each other:
gc_entertakes the VM lock and callsrb_gc_vm_barrier()— commented stop other ractors — so every GC, minor ones included, pauses all Ractors.- Each Ractor allocates from its own cache of free slots; when the cache is empty,
newobj_cache_misstakes the cross-Ractor lock to get more.
Reading GC.stat around the timed reps shows the cost (same cells, a control run in each pass, 9 trials):
| Per rep (512 tasks) | String alloc, 1 Ractor | String alloc, 8 Ractors | JSON.parse, 1 Ractor | JSON.parse, 8 Ractors |
|---|---|---|---|---|
| GC runs | 274 | 93 | 57 | 16 |
| time in GC | 55.0 ms | 114.0 ms | 16.4 ms | 22.3 ms |
| time per GC | 0.20 ms | 1.22 ms | 0.29 ms | 1.36 ms |
| share of wall time in GC | 16 % | 30 % | 21 % | 33 % |
| wall time outside GC | 278 ms | 264 ms | 61 ms | 46 ms |
With 8 Ractors the collector runs a third to a quarter as often, but each run takes 6.1× longer (String) and 4.7× longer (JSON), because it marks and sweeps the objects of all eight and stops all eight. The time outside GC barely shrinks either: 278 ms of String building with 1 Ractor takes 264 ms with 8 (a perfect split would be 35 ms), so the time that 8 cores should have saved is lost waiting, at the GC barrier and on the VM lock that refills each Ractor’s slot cache (GC.stat[:time] counts neither wait, so this measurement cannot split the two). fork avoids both because nothing is shared.
A bigger starting heap removes most of it. With RUBY_GC_HEAP_0_INIT_SLOTS to RUBY_GC_HEAP_4_INIT_SLOTS set to 1,000,000, 8 Ractors ran 3.0× one thread on Strings, 2.8× on Hashes and 2.6× on JSON.parse (0.9–1.1× by default), with 0.6–3.2 collections per rep instead of 17–93 and 59–129 MB peak memory instead of 19 MB. Switching the collector off was no better: 3.1× on Strings, 1.9× on Hashes and JSON.parse. With no collections, every slot-cache refill has to grow the heap, inside the same cross-Ractor lock. Details in the benchmark article.
YJIT and non-allocating work
The same fib and Float cells without YJIT:
| 1 Ractor | 8 Ractors | 1 × fork | 8 × fork | |
|---|---|---|---|---|
fib, interpreter | 574 | 3,902 (6.8×) | 575 | 4,579 (8.0×) |
fib, YJIT | 2,177 | 11,303 (5.2×) | 2,341 | 18,235 (7.8×) |
| Float loop, interpreter | 524 | 3,588 (6.8×) | 525 | 4,175 (8.0×) |
| Float loop, YJIT | 1,271 | 7,350 (5.8×) | 1,270 | 10,047 (7.9×) |
YJIT makes each Ractor 3.8× faster on fib but the 8-Ractor speed-up drops from 6.8× to 5.2×, and one Ractor runs YJIT code 7 % slower than a thread or a forked child (2,177 against 2,340 and 2,341 tasks per second; without YJIT a Ractor and a forked child are equal, 574 and 575). fork keeps 7.8–8.0× either way. With YJIT, the best Ractor cases reach 62–83 % of what fork does on 8 cores (85 % for fib in the interpreter).
Measured: 28 whole programs
The six workloads above are fragments. The same three models also ran the 28 programs from Spinel vs JRuby vs CRuby, each split into 8 identical tasks:
- Programs that allocate little scale: the 14 that allocate under 0.11 million objects per second on one thread reach 5.3–7.9×,
partial_sums,matmulandlifethe most. - Programs that allocate a lot do not: the 13 that allocate 2.4 million or more reach 0.26–2.0×;
binary_trees0.77×,json_parse0.77×,template0.80× andsplay0.26× are slower than one thread. forkreaches 6.5–8.0× on all 28.
Read more: all 28 programs, memory, GC settings and task size →
Measured: the cost of a message
One echo Ractor on 2 cores: send one Array of n Strings of 100 B, wait for a one-integer reply. The Queue column is the same round trip between two threads, where nothing is copied.
Ractor.make_shareable on the same payload.Ractor.make_shareable on the same payload.| Payload | Queue (threads) | Ractor: copy | Ractor: move: true | Ractor: shareable | make_shareable, once |
|---|---|---|---|---|---|
| 1 String, 100 B | 10.2 µs | 10.8 µs | 10.4 µs | 9.5 µs | 3.5 µs |
| 10 Strings, 1 KB | 10.0 µs | 14.2 µs | 11.7 µs | 9.5 µs | 5.4 µs |
| 100 Strings, 10 KB | 10.0 µs | 45.0 µs | 30.2 µs | 9.6 µs | 19.5 µs |
| 1,000 Strings, 100 KB | 10.3 µs | 433 µs | 235 µs | 9.8 µs | 119 µs |
| 10,000 Strings, 1 MB | 10.9 µs | 4.62 ms | 2.33 ms | 10.0 µs | 1.45 ms |
| 100,000 Strings, 10 MB | 10.9 µs | 50.7 ms | 20.6 ms | 10.3 µs | 17.4 ms |
- A small message costs about the same as a Queue hand-off between threads: 10.8 µs against 10.2 µs.
- A copy grows with the number of objects: 0.46 µs per 100 B String at 1 MB, 0.51 µs at 10 MB. Copying 1 MB takes 4.62 ms, about 420 times the round trip itself.
move: trueis 1.8× cheaper than a copy at 100 KB and 2.0–2.5× at 1–10 MB, but it still walks every object, so it grows the same way.- A shareable object costs nothing extra at any size (9.5–10.3 µs). Making it shareable costs one walk over the graph: 1.45 ms for 1 MB, 17.4 ms for 10 MB, paid once.
Measured: starting one, and what it weighs
| One core, median | Thread | Ractor | fork |
|---|---|---|---|
| create, run an empty block, wait for it | 33.4 µs | 20.7 µs | 832 µs |
resident memory per idle worker (200 workers that each ran fib(15), then wait on a receive) | 33.3 KB | 21.7 KB | — |
A Ractor starts faster than a Thread here and holds less memory while it waits. Spawn cost does not decide between them; fork is 40× slower to start than a Ractor, which is why servers fork their workers once at boot.
Pitfalls
- Gems are the usual blocker. A gem that memoises into a constant Hash, keeps a class-level cache or reads a
$globalraisesRactor::IsolationErrorthe first time a Ractor calls it. Check a gem by running its hot path insideRactor.new { … }.valuebefore you design around it. selfinside the block is the Ractor. A baresend(:method_name, …)in a Ractor block callsRactor#sendand posts a message to itself; it does not call your method. Use__send__orpublic_send.- A dead Ractor is silent. An exception in a worker that is never
#joined or#valued leaves the caller blocked on its port for good.r.monitor(port)turns the death into a message. make_shareablefreezes your object. It deep-freezes in place; a later<<on that Array raisesFrozenErrorin the main Ractor as well. Passcopy: trueto freeze a copy instead.- Big messages cost what a deep copy costs. A 1 MB Array of Strings takes milliseconds to
send; share it once or send an index into shared data.
When to use Ractors
| Work | Use |
|---|---|
| Web requests, I/O, database calls | threads (Puma), or fibers with async; the GVL is released while waiting |
| CPU-bound Ruby code over integers, floats, existing Symbols, frozen data | Ractors: 4.8–6.4× on 8 cores here, one process, no serialisation |
| CPU-bound code that allocates: building Strings, Hashes, parsing JSON | fork: 7.6–7.9× on 8 cores; Ractors stay at 0.9–1.2× |
| Large inputs read by every worker | share once with Ractor.make_shareable, or fork after loading them (copy-on-write) |
| Code that calls gems you do not control | fork or threads, until each gem is checked inside a Ractor |
Related
- Ruby vs Python concurrency — GVL vs GIL; Ractors next to subinterpreters, measured on 4 cores.
- Ruby vs Elixir concurrency — Ractors and fork next to BEAM processes.
- JavaScript vs Ruby concurrency — event loop vs GVL.
- Ruby vs Rust benchmarks: eight everyday fragments — includes threads, Ractors and fork on
cpu,jsonandioat 1–8 cores on x86. - Which language is best for concurrency? — Ruby, Python, Elixir, Java, C++ and JavaScript side by side.
Method
| Setup | Details |
|---|---|
| Ruby | 4.0.9, image pinned by digest (ruby@sha256:3251898a…2cd31d, full digest in the commands below; what the ruby:4.0-slim tag pointed to at the time of the run — a tag moves, a digest does not), arm64, --yjit unless a row says interpreter · json 2.18.0 |
| CPU | 20-core ARM64 server (10 × Cortex-X925 + 10 × Cortex-A725). Benchmarks on the A725 cores at 2.8 GHz, governor performance: W = 1, 2, 4, 8 on --cpuset-cpus=1, 1-2, 1-4, 1-4,10-13 |
| Isolation | For the whole run, every systemd service, every other container and every movable IRQ was confined to the ten X925 cores (cgroup v2 cpuset.cpus on system.slice, user.slice, init.scope); the benchmark containers ran in their own slice. Each cell measured foreign CPU time on its cores from /proc/stat minus its own slice, and was discarded and re-run above 0.05 + 0.03 × W cores; also re-run (after a 30 s wait) when the rest of the machine used more than 5 cores or the GPU, which shares the memory, was more than 5 % busy. |
| Why not the X925 cores | With --yjit, 64 × fib(22) on one X925 core took 0.145–0.153 s in most processes and 0.011 s in a few, depending on address layout (ASLR on/off, environment size); the interpreter took 0.066 s. The A725 cores gave 0.0274–0.0277 s in 18 of 18 processes, and fib on one Ractor ran 2,176–2,178 tasks per second in all 9 trials |
| Scale cells | Persistent workers (W threads fed by a Queue, W Ractors fed by Ractor#send and answering on one Ractor::Port, W forked children fed over pipes — the shape of a Puma cluster). 2 warm-up reps, then ≥ 5 reps and ≥ 3 s; the median rep. The same total tasks at every W; checksums equal across models and W |
| Message cells | One echo Ractor on 2 cores; one send + a one-integer reply per sample; 3 warm-up sends, then 20–2,000 samples, median. Payload: an Array of n Strings of 100 B. move: sends a fresh payload each time (built before timing) |
| Trials | 3 passes × 3 interleaved trials (every cell once, then again); the median of the 9 is reported |
Each cell runs in a fresh container; rb.rb prints one JSON line per cell (checksum, tasks per second or µs, peak RSS):
docker run --rm --cgroup-parent=bench651.slice --cpuset-cpus=1-4,10-13 -v "$PWD":/b -w /b \
ruby@sha256:3251898a6b7ff1275a0dc279d401889c6c743c1fb3292fa3ce1a2e12fc2cd31d \
ruby --yjit rb.rb scale json ractors 8
docker run --rm --cgroup-parent=bench651.slice --cpuset-cpus=1-2 -v "$PWD":/b -w /b \
ruby@sha256:3251898a6b7ff1275a0dc279d401889c6c743c1fb3292fa3ce1a2e12fc2cd31d \
ruby --yjit rb.rb msg move 10000
The GC.stat table and the interpreter rows come from a control run of the scale cells with rb2.rb in each pass: rb.rb plus GC.stat read around the timed reps (GC.stat[:time] is in ms and is one VM-wide counter for all Ractors). The interpreter rows ran it without --yjit. The whole difference:
@@ -75,13 +75,17 @@
sums = []; times = []
t_end = now + 3.0; reps = 0
2.times { sums << rep.call } # warm-up
+ g0 = GC.stat.slice(:count, :time, :minor_gc_count, :major_gc_count)
while reps < 5 || now < t_end
t = now; sums << rep.call; times << now - t; reps += 1
end
+ g1 = GC.stat.slice(:count, :time, :minor_gc_count, :major_gc_count)
abort "checksum drift #{sums.uniq}" unless sums.uniq.size == 1
t = median(times)
+ gc = { gc_per_rep: ((g1[:count] - g0[:count]) / reps.to_f).round(2), gc_ms_per_rep: ((g1[:time] - g0[:time]) / reps.to_f).round(2),
+ gc_share: ((g1[:time] - g0[:time]) / 1000.0 / times.sum).round(4) }
emit(test: "scale", workload: wl, model: model, w: w, tasks: total, reps: reps, median_s: t.round(6),
- tasks_per_s: (total / t).round(1), checksum: sums[0], peak_rss_kb: rss_kb("VmHWM"))
+ tasks_per_s: (total / t).round(1), checksum: sums[0], peak_rss_kb: rss_kb("VmHWM"), **gc)
end
# ---------- msg: one message to an echo Ractor and a 1-int reply ----------
rb.rb:
# Ractor benchmarks (Ruby 4.0). One JSON line per run on stdout.
# ruby --yjit rb.rb scale <workload> <model> <W> workload: int float str hash json sym ; model: threads ractors fork
# ruby --yjit rb.rb msg <mode> <n> mode: thread copy move shareable ; n = strings of 100 B in the payload
# ruby --yjit rb.rb spawn <model> model: thread ractor fork
# ruby --yjit rb.rb mem <model> model: thread ractor (RSS per idle worker)
require "json"
Warning[:experimental] = false
def now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
def median(a) = a.sort[a.size / 2]
def rss_kb(f = "VmRSS") = File.read("/proc/self/status")[/#{f}:\s+(\d+)/, 1].to_i
def emit(h) = puts(JSON.generate(h.merge(ruby: RUBY_VERSION, yjit: defined?(RubyVM::YJIT) && RubyVM::YJIT.enabled?, cpus: Etc.nprocessors)))
require "etc"
# ---------- workloads: task(i) -> Integer; every task does the same amount of work ----------
def fib(n) = n < 2 ? n : fib(n - 1) + fib(n - 2)
def w_int(i) = fib(22) + i
def w_float(i) # flonums: no heap allocation on 64-bit
x = 0.0; y = 0.0; k = 0
20_000.times { |j| x = x * 0.5 + (j + i) * 1.0e-3; y += x * x; k += 1 }
(y * 1000).to_i + k
end
def w_str(i) # 2,000 short String objects
a = Array.new(2_000) { |j| "item-#{i}-#{j}" }
a.sum(&:bytesize)
end
def w_hash(i) # 500 Hash rows with a nested Array
rows = Array.new(500) { |j| { id: j, name: "n#{j}", tags: [i, j, i + j] } }
rows.sum { |r| r[:id] + r[:tags].sum + r[:name].bytesize }
end
DOC = Ractor.make_shareable(JSON.generate(Array.new(200) { |j| { "id" => j, "name" => "user-#{j}", "score" => j * 0.5, "tags" => %w[a b c], "active" => j.odd? } }))
def w_json(i) # parse a 15 KB document
JSON.parse(DOC).sum { |r| r["id"] + r["name"].bytesize + r["tags"].size } + i
end
def w_sym(i) # 2,000 String -> Symbol lookups (all symbols already exist)
s = 0
2_000.times { |j| s += SYMSTR[(i + j) % 1000].to_sym.size }
s
end
SYMSTR = Ractor.make_shareable(Array.new(1000) { |j| "sym_#{j}" })
SYMSTR.each(&:to_sym)
TASKS = { "int" => 256, "float" => 256, "str" => 512, "hash" => 512, "json" => 512, "sym" => 1024 }
def run_share(wl, ids) = ids.sum { |i| __send__(:"w_#{wl}", i) } # not send: inside a Ractor block self is the Ractor, and Ractor#send is messaging
# ---------- scale ----------
def scale(wl, model, w)
total = TASKS.fetch(wl)
shares = Array.new(w) { |k| (k...total).step(w).to_a }
rep = case model
when "threads"
qs = Array.new(w) { Queue.new }; out = Queue.new
w.times { |k| Thread.new { while qs[k].pop; out << run_share(wl, shares[k]); end } }
-> { qs.each { _1 << true }; Array.new(w) { out.pop }.sum }
when "ractors"
out = Ractor::Port.new
rs = Array.new(w) { |k| Ractor.new(wl, shares[k], out) { |wl, ids, out| while Ractor.receive; out << run_share(wl, ids); end } }
-> { rs.each { _1.send(true) }; Array.new(w) { out.receive }.sum }
when "fork"
kids = Array.new(w) do |k|
cr, cw = IO.pipe; pr, pw = IO.pipe
pid = fork { cw.close; pr.close; while cr.gets; pw.puts run_share(wl, shares[k]); end; exit! 0 }
cr.close; pw.close; [cw, pr, pid]
end
-> { kids.each { |cw, _, _| cw.puts "go" }; kids.sum { |_, pr, _| pr.gets.to_i } }
else abort "model?"
end
sums = []; times = []
t_end = now + 3.0; reps = 0
2.times { sums << rep.call } # warm-up
while reps < 5 || now < t_end
t = now; sums << rep.call; times << now - t; reps += 1
end
abort "checksum drift #{sums.uniq}" unless sums.uniq.size == 1
t = median(times)
emit(test: "scale", workload: wl, model: model, w: w, tasks: total, reps: reps, median_s: t.round(6),
tasks_per_s: (total / t).round(1), checksum: sums[0], peak_rss_kb: rss_kb("VmHWM"))
end
# ---------- msg: one message to an echo Ractor and a 1-int reply ----------
def payload(n) = Array.new(n) { |j| ("x" * 92) + format("%08d", j) } # n strings of 100 B
def msg(mode, n)
iters = [[200_000 / [n, 1].max, 20].max, 2_000].min
if mode == "thread"
q = Queue.new; back = Queue.new
Thread.new { while (o = q.pop); back << o.size; end }
obj = payload(n)
send1 = ->(_) { q << obj; back.pop }
else
back = Ractor::Port.new
r = Ractor.new(back) { |b| while (o = Ractor.receive); b << o.size; end }
case mode
when "copy" then obj = payload(n); send1 = ->(_) { r.send(obj); back.receive }
when "move" then pool = Array.new(iters + 3) { payload(n) }; send1 = ->(k) { r.send(pool[k], move: true); back.receive }
when "shareable"
obj = payload(n)
t = now; Ractor.make_shareable(obj); share_s = now - t
send1 = ->(_) { r.send(obj); back.receive }
else abort "mode?"
end
end
3.times { |k| abort "bad reply" unless send1.(k) == n }
ts = Array.new(iters) { |k| t = now; abort "bad reply" unless send1.(k + 3) == n; now - t }
emit(test: "msg", mode: mode, n: n, bytes: n * 100, iters: iters, median_us: (median(ts) * 1e6).round(2),
p10_us: (ts.sort[iters / 10] * 1e6).round(2), make_shareable_us: share_s && (share_s * 1e6).round(1), checksum: n)
end
# ---------- spawn: create one worker, run an empty block, wait for it ----------
def spawn_cost(model)
one = case model
when "thread" then -> { Thread.new { 1 }.value }
when "ractor" then -> { Ractor.new { 1 }.value }
when "fork" then -> { pid = fork { exit! 0 }; Process.wait(pid); 1 }
else abort "model?"
end
n = model == "fork" ? 300 : 2_000
50.times { one.() }
ts = Array.new(n) { t = now; one.(); now - t }
emit(test: "spawn", model: model, n: n, median_us: (median(ts) * 1e6).round(2), p90_us: (ts.sort[n * 9 / 10] * 1e6).round(2), checksum: 1)
end
# ---------- mem: RSS added by 200 idle workers that each ran fib(15) once ----------
def mem(model)
n = 200
GC.start; base = rss_kb
ws = case model
when "thread" then Array.new(n) { q = Queue.new; [Thread.new { fib(15); q.pop }, q] }
when "ractor" then Array.new(n) { Ractor.new { fib(15); Ractor.receive } }
else abort "model?"
end
sleep 0.5; GC.start; after = rss_kb
model == "thread" ? ws.each { |t, q| q << 1; t.join } : ws.each { |r| r.send(1); r.join }
emit(test: "mem", model: model, n: n, kb_per_worker: ((after - base) / n.to_f).round(1), checksum: n)
end
case ARGV[0]
when "scale" then scale(ARGV[1], ARGV[2], Integer(ARGV[3]))
when "msg" then msg(ARGV[1], Integer(ARGV[2]))
when "spawn" then spawn_cost(ARGV[1])
when "mem" then mem(ARGV[1])
else abort "usage: see header"
end