Ruby vs Python concurrency
Ruby and Python made the same choice: real OS threads, and one lock that lets only one of them run interpreter code at a time. Python has had its lock since its first thread support in the early 1990s, Ruby since 1.9 (2007) moved from green threads to native ones. Ruby calls it the GVL, Python the GIL. Today they differ in the details that decide latency and scaling. How often the lock changes hands, what replaces threads for 10,000 connections, and how you get a second core: Ractors and fork in Ruby; processes, subinterpreters and a GIL-free build in Python.
At a glance
| Ruby (MRI 4.0) | Python (CPython 3.14) | |
|---|---|---|
| The lock | GVL (Global VM Lock) | GIL (Global Interpreter Lock) |
| Time slice before a CPU-bound thread is preempted | 100 ms (TIME_QUANTUM_MSEC) | 5 ms (sys.getswitchinterval(), settable) |
| Released on | blocking I/O, sleep, Queue#pop, C code calling rb_thread_call_without_gvl | blocking I/O, time.sleep, C code using Py_BEGIN_ALLOW_THREADS (NumPy, hashlib, zlib) |
| Lightweight tasks | Fiber + Fiber::Scheduler (the async gem): existing Net::HTTP, sleep, sockets become non-blocking | asyncio coroutines: needs async def/await and async libraries |
| Many threads, few OS threads | M:N threads (RUBY_MN_THREADS=1, 3.3+) | — |
| Parallel interpreter code in one process | Ractor (experimental): one GVL each | subinterpreters (3.14, concurrent.interpreters): one GIL each · free-threaded build (python3.14t): no GIL |
| Parallel processes | fork, Puma workers, Sidekiq processes | multiprocessing, ProcessPoolExecutor (forkserver by default on Linux since 3.14), gunicorn workers |
The two locks
- Both locks protect the same thing: interpreter internals (object allocation, reference counts or the GC, C extensions written without fine-grained locking).
- Both are released while a thread blocks in the kernel, so threads still overlap database and network waits — what a web request mostly does.
- The difference is the time slice. A CPU-bound Ruby thread keeps the GVL for 100 ms before the VM hands it to a waiting thread. Python asks for the GIL back after 5 ms. A request thread whose database answer arrived waits up to 100 ms in Ruby, up to 5 ms in Python. The lag test below measures those two numbers: 100.6 ms and 5.2 ms.
- The short slice costs lock hand-offs: four CPU-bound Python threads run 9 % slower than one loop (2.442 s vs 2.233 s); four Ruby threads run as fast as one loop (0.271 s vs 0.278 s).
Beyond the lock
Ruby
Ractor: each Ractor has its own GVL. Objects passed between Ractors are copied, moved or deep-frozen (Ractor.make_shareable). Still marked experimental in 4.0 (it prints a warning), and most gems are not Ractor-safe.fork: a copy-on-write child process. This is how Puma (workers) and Sidekiq (processes) use more than one core.- Fibers +
Fiber::Scheduler(Ruby 3.0+): with theasyncgem installed as scheduler, blocking calls in ordinary code yield the fiber instead of the thread. Noawaitkeyword, and no separate async library ecosystem.
Python
- Processes:
multiprocessing/ProcessPoolExecutor. Arguments and results are pickled; on Linux the default start method becameforkserverin 3.14 (it wasfork). - Subinterpreters: one GIL per interpreter since 3.12 (PEP 684), usable from Python code since 3.14 (
concurrent.interpreters,InterpreterPoolExecutor, PEP 734). - The free-threaded build (PEP 703): no GIL at all. Experimental in 3.13, supported but not the default in 3.14, installed as
python3.14t. C extensions must declare support, or the interpreter turns the GIL back on at import. asyncio: coroutines on one event loop, switching only atawait. Libraries must be async-aware (httpx,asyncpg); a sync call inside a coroutine blocks the loop.
Measured: four tests, same 4 cores
Ruby 4.0.9 with YJIT, CPython 3.14.10 (GIL build and free-threaded build), all in Docker on the same 4 cores (--cpuset-cpus=8-11 of an AMD Ryzen AI Max+ 395). Median of rounds 2–4 (of 4; see Method). Scripts and commands are at the end.
1. CPU-bound: 4 × fib(35)
| Ruby | wall | speed-up | Python | wall | speed-up |
|---|---|---|---|---|---|
| sequential | 0.278 s | 1.0× | sequential | 2.233 s | 1.0× |
| 4 threads | 0.271 s | 1.0× | 4 threads (GIL build) | 2.442 s | 0.91× |
| 4 Ractors | 0.080 s | 3.5× | 4 subinterpreters | 0.689 s | 3.2× |
4 processes (fork) | 0.073 s | 3.8× | 4 processes (ProcessPoolExecutor) | 0.703 s | 3.2× |
| free-threaded: sequential | 2.011 s | 1.0× | |||
| free-threaded: 4 threads | 0.549 s | 3.7× |
- Per core, Ruby with YJIT runs this code 8.0× faster than CPython (0.278 s vs 2.233 s). One Ruby core beats four Python cores (0.278 s vs 0.549 s at best).
- Against a perfect 4× split (0.278 / 4 = 0.0695 s), Ractors take 10.5 ms longer and
fork3.5 ms. Python’s processes take 145 ms longer, subinterpreters 131 ms (2.233 / 4 = 0.558 s), free-threaded threads 46 ms (2.011 / 4 = 0.503 s). A likely reason: Python’s pools start fresh interpreters (subinterpreters, or workers forked from a newly started forkserver), while Ruby’sforkcopies the running, warmed-up process. - The two Python builds come from different toolchains (official image, GCC 14.2; uv’s python-build-standalone, Clang 23), so compare each build with itself.
2. I/O-bound: 10,000 concurrent 100 ms waits
| Runtime · primitive | wall | over the 0.100 s ideal | RSS |
|---|---|---|---|
| Python · 10,000 asyncio tasks | 0.143 s | +43 ms | 34 MB |
Ruby · 10,000 threads, M:N (RUBY_MN_THREADS=1) | 0.335 s | +235 ms | 147 MB |
Ruby · 10,000 fibers (async 2.46) | 0.360 s | +260 ms | 133 MB |
| Python · 10,000 threads (GIL build) | 0.396 s | +296 ms | 60 MB |
| Ruby · 10,000 threads (default 1:1) | 1.092 s | +992 ms | 192 MB |
| Python free-threaded · 10,000 threads | 1.185 s | +1,085 ms | 275 MB |
- asyncio is the cheapest way to hold 10,000 waits here: 2.5× faster than Ruby fibers, a quarter of the memory.
- Plain OS threads: Python finishes the test 2.8× sooner than Ruby’s default 1:1 threads, using a third of the memory. Ruby’s M:N scheduler closes that gap.
- Ruby fibers need no code change: the same
sleepandNet::HTTPcalls become non-blocking under the scheduler. asyncio needsasync/awaitall the way down.
3. Shared counter: 4 × 1,000,000 increments
| Code | Result (expected 4,000,000) |
|---|---|
Ruby · 4 threads · c += 1 | 4,000,000 (3 / 3 runs) |
Ruby · v = c; Thread.pass; c = v + 1 | 1,000,000 (3 / 3) |
Ruby · same, inside Mutex#synchronize | 4,000,000 |
Python GIL build · 4 threads · c += 1 | 4,000,000 (3 / 3) |
Python GIL build · v = c; time.sleep(0); c = v + 1 | 1,000,000 (1,000,000 – 1,000,003) |
Python GIL build · same, inside with lock: | 4,000,000 |
Python free-threaded · 4 threads · c += 1 | 3,252,428 (3,250,418 – 3,343,234) |
Python · 4 asyncio tasks · v = c; await asyncio.sleep(0); c = v + 1 | 1,000,000 (3 / 3) |
- Both locks happen to make
c += 1safe: neither interpreter hands the lock over between that line’s read and write. That is an implementation detail. Python’s free-threaded build loses 19 % of the updates on the same line, and JRuby, which has no GVL, loses about 60 % (measured in JavaScript vs Ruby concurrency). - Put a lock release between the read and the write and both lose 75 %: the four threads read the same value, so four increments become one. An
awaitin asyncio does the same.
4. A blocked timer: 10 ms ticker next to a CPU-bound thread
| Runtime · where the CPU work runs | CPU task | worst ticker lateness |
|---|---|---|
Ruby · another Thread, fib(37) | 177 ms | 100.6 ms |
Ruby · a Ractor, fib(37) | 184 ms | 0.4 ms |
Python GIL build · another thread, fib(32) | 173 ms | 5.2 ms |
Python free-threaded · another thread, fib(32) | 120 ms | 0.2 ms |
Python · a process, fib(32) | 231 ms | 3.2 ms |
Python · on the asyncio loop, fib(32) | 136 ms | 135.7 ms |
- Similar CPU tasks (173–184 ms), very different waits: one Ruby time slice is 100 ms, one Python switch interval is 5 ms.
- In a Puma or Sidekiq process, a CPU-heavy thread can add up to 100 ms to every other thread’s response. Python threads add at most a few ms. Python’s asyncio has no preemption, so a coroutine that never awaits blocks everything for its full duration.
- Moving the work into a second interpreter (Ractor, process, free-threaded thread) brings both down to below 4 ms.
The same task in both
Three HTTP requests at once:
# Ruby, fibers — Net::HTTP becomes non-blocking under the Fiber scheduler
require "async"
bodies = Async { |task| urls.map { |u| task.async { Net::HTTP.get(URI(u)) } }.map(&:wait) }.wait
# Python, asyncio — needs an async client; requests would block the loop
import asyncio, httpx
async def main(urls):
async with httpx.AsyncClient() as client:
return [r.text for r in await asyncio.gather(*(client.get(u) for u in urls))]
A CPU-heavy job on another core:
# Ruby — a Ractor has its own GVL; the block may only touch shareable objects
total = Ractor.new(rows) { |rows| rows.sum { |row| expensive(row) } }.value
# Python — a process pool; on the free-threaded build a ThreadPoolExecutor works too
from concurrent.futures import ProcessPoolExecutor
with ProcessPoolExecutor() as pool:
total = sum(pool.map(expensive, rows))
Pitfalls
| Ruby | Python |
|---|---|
| A CPU-heavy thread (rendering, JSON, image work) delays every other thread by up to 100 ms | Four CPU-bound threads are slower than one: 0.91× here |
| Code that is safe only because of the GVL (`@x | |
| Ractors: most gems are not Ractor-safe (non-shareable constants, global state) | Subinterpreters: C extensions must support multiple interpreters; objects do not cross interpreters |
fork after threads start: only the forking thread survives in the child | fork after threads start is why 3.14 moved Linux to forkserver; pools pickle every argument |
Timeout.timeout raises into a thread at any line, even inside ensure | A sync library call inside a coroutine blocks the whole event loop |
Which one for what
| Workload | Ruby | Python |
|---|---|---|
| Request/response web app, DB-bound | Puma: threads × processes | gunicorn/uvicorn: workers × threads or asyncio |
| 10,000+ idle connections | fibers (async, Falcon) or M:N threads | asyncio |
| CPU work in Ruby/Python code | fork/Sidekiq processes, Ractors | processes, subinterpreters, the free-threaded build |
| Numeric work | a native extension or another service | NumPy and friends release the GIL inside C |
Related
- JavaScript event loop — paste code, step the tasks and queues — the simulator: tasks, microtasks and timers, checked against the real engine.
- JavaScript vs Ruby concurrency — event loop vs GVL, measured on 4 cores.
- Python vs JavaScript concurrency — GIL, asyncio and free-threaded Python vs the event loop, measured on 4 cores.
- Concurrency battle! Which language wins? — Ruby, Python, Elixir, Java, C++ and JavaScript side by side.
Method
| Setup | Details |
|---|---|
| Ruby | 4.0.9, image ruby:4.0, --yjit; async 2.46.0 |
| Python | 3.14.10, GIL build from image python:3.14 (GCC 14.2) · free-threaded 3.14.10t installed with uv python install 3.14t (python-build-standalone, Clang 23) |
| CPU | AMD Ryzen AI Max+ 395, 4 cores (docker --cpuset-cpus=8-11), host not isolated |
| Runs | 4 rounds of every test; round 1 dropped (an unrelated container briefly shared the cores); median of rounds 2–4, ranges where the spread matters · 1-minute load average 9.2, 16.8 and 18.5 at the start of rounds 2, 3 and 4 |
docker run --rm --cpuset-cpus=8-11 -e GEM_HOME=/b/gems -v "$PWD":/b -w /b ruby:4.0 gem install async --no-document
docker run --rm --cpuset-cpus=8-11 -e GEM_HOME=/b/gems -v "$PWD":/b -w /b ruby:4.0 ruby --yjit conc.rb lag thread
docker run --rm --cpuset-cpus=8-11 -v "$PWD":/b -w /b python:3.14 python conc.py lag thread
docker run --rm -v "$PWD":/b -w /b -e UV_PYTHON_INSTALL_DIR=/b/pythons python:3.14 sh -c 'pip install uv && uv python install 3.14t'
docker run --rm --cpuset-cpus=8-11 -v "$PWD":/b -w /b python:3.14 /b/pythons/cpython-3.14.10+freethreaded-linux-x86_64-gnu/bin/python3.14t conc.py race plain
conc.rb:
# Ruby side of the concurrency comparisons. Usage: ruby conc.rb <test> <mode>
require "etc"
def now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
def rss_mb = File.read("/proc/self/status")[/VmRSS:\s+(\d+)/, 1].to_i / 1024.0
def fib(n) = n < 2 ? n : fib(n - 1) + fib(n - 2)
N_CPU = 4; FIB = 35; N_IO = 10_000; WAIT = 0.1
test, mode = ARGV
case test
when "cpu" # 4 × fib(35), sequential vs threads vs ractors vs forked processes
t = now
case mode
when "seq" then N_CPU.times { fib(FIB) }
when "threads" then N_CPU.times.map { Thread.new { fib(FIB) } }.each(&:join)
when "ractors"
rs = N_CPU.times.map { Ractor.new { def f(n) = n < 2 ? n : f(n - 1) + f(n - 2); f(35) } }
rs.each(&:value)
when "fork" then N_CPU.times.map { fork { fib(FIB) } }.each { Process.wait(_1) }
end
puts format("cpu %-8s %.3f s", mode, now - t)
when "io" # 10,000 concurrent 100 ms waits
t = now
case mode
when "threads" then N_IO.times.map { Thread.new { sleep WAIT } }.each(&:join)
when "fibers"
require "async"
Async { |task| N_IO.times.map { task.async { sleep WAIT } }.each(&:wait) }
end
puts format("io %-8s %.3f s rss %.0f MB", mode, now - t, rss_mb)
when "race" # 4 threads × 1,000,000 increments of one shared counter
c = 0; m = Mutex.new
ths = 4.times.map do
Thread.new do
case mode
when "plain" then 1_000_000.times { c += 1 }
when "mutex" then 1_000_000.times { m.synchronize { c += 1 } }
when "yield" then 1_000_000.times { v = c; Thread.pass; c = v + 1 } # GVL released between read and write, as any I/O call does
when "yield_mutex" then 1_000_000.times { m.synchronize { v = c; Thread.pass; c = v + 1 } }
end
end
end
ths.each(&:join)
puts "race #{mode} #{c} (expected 4000000)"
when "lag" # a 10 ms ticker next to a CPU-bound thread: worst lateness
worst = 0.0; stop = false
ticker = Thread.new do
until stop
t = now; sleep 0.01; late = now - t - 0.01; worst = late if late > worst
end
end
sleep 0.05
t0 = now
case mode
when "thread" then Thread.new { fib(37) }.join
when "ractor" then Ractor.new { def f(n) = n < 2 ? n : f(n - 1) + f(n - 2); f(37) }.value
end
took = now - t0
stop = true; ticker.join
puts format("lag %-8s worst ticker lateness %.1f ms (cpu task %.0f ms)", mode, worst * 1000, took * 1000)
end
conc.py:
# Python side of the concurrency comparisons. Usage: python conc.py <test> <mode>
import asyncio, sys, threading, time
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
def now(): return time.monotonic()
def rss_mb():
with open("/proc/self/status") as f:
return int(next(l for l in f if l.startswith("VmRSS")).split()[1]) / 1024
def fib(n): return n if n < 2 else fib(n - 1) + fib(n - 2)
N_CPU, FIB, N_IO, WAIT = 4, 35, 10_000, 0.1
LAG_FIB = 32
def cpu(mode):
t = now()
if mode == "seq":
for _ in range(N_CPU): fib(FIB)
elif mode == "threads":
with ThreadPoolExecutor(N_CPU) as ex: list(ex.map(fib, [FIB] * N_CPU))
elif mode == "asyncio":
async def task(): return fib(FIB)
async def main(): await asyncio.gather(*(task() for _ in range(N_CPU)))
asyncio.run(main())
elif mode == "processes":
with ProcessPoolExecutor(N_CPU) as ex: list(ex.map(fib, [FIB] * N_CPU))
elif mode == "interpreters": # PEP 734, Python 3.14+
from concurrent.futures import InterpreterPoolExecutor
with InterpreterPoolExecutor(N_CPU) as ex: list(ex.map(fib, [FIB] * N_CPU))
print(f"cpu {mode:<12} {now() - t:.3f} s")
def io(mode):
t = now()
if mode == "asyncio":
async def main(): await asyncio.gather(*(asyncio.sleep(WAIT) for _ in range(N_IO)))
asyncio.run(main())
elif mode == "threads":
ts = [threading.Thread(target=time.sleep, args=(WAIT,)) for _ in range(N_IO)]
for th in ts: th.start()
for th in ts: th.join()
print(f"io {mode:<12} {now() - t:.3f} s rss {rss_mb():.0f} MB")
def race(mode):
c = 0
lock = threading.Lock()
def plain():
nonlocal c
for _ in range(1_000_000): c += 1
def yielding(): # GIL released between read and write, as any blocking call does
nonlocal c
for _ in range(1_000_000):
v = c; time.sleep(0); c = v + 1
def locked():
nonlocal c
for _ in range(1_000_000):
with lock: c += 1
if mode == "await": # 4 asyncio tasks, an await between read and write
async def task():
nonlocal c
for _ in range(1_000_000):
v = c; await asyncio.sleep(0); c = v + 1
async def main(): await asyncio.gather(*(task() for _ in range(4)))
asyncio.run(main())
else:
fn = {"plain": plain, "yield": yielding, "lock": locked}[mode]
ts = [threading.Thread(target=fn) for _ in range(4)]
for th in ts: th.start()
for th in ts: th.join()
print(f"race {mode} {c} (expected 4000000)")
def lag(mode):
worst = 0.0
if mode in ("thread", "process"):
stop = False
def ticker():
nonlocal worst
while not stop:
t = now(); time.sleep(0.01); worst = max(worst, now() - t - 0.01)
th = threading.Thread(target=ticker); th.start()
time.sleep(0.05)
t = now()
if mode == "thread":
w = threading.Thread(target=fib, args=(LAG_FIB,)); w.start(); w.join()
else:
with ProcessPoolExecutor(1) as ex: ex.submit(fib, LAG_FIB).result()
took = now() - t
stop = True; th.join()
else: # asyncio: the CPU call runs on the event loop
async def main():
nonlocal worst
done = False
async def ticker():
nonlocal worst
while not done:
t = now(); await asyncio.sleep(0.01); worst = max(worst, now() - t - 0.01)
tk = asyncio.create_task(ticker())
await asyncio.sleep(0.05)
t = now(); fib(LAG_FIB); took = now() - t
await asyncio.sleep(0.03)
done = True; await tk
return took
took = asyncio.run(main())
print(f"lag {mode:<8} worst ticker lateness {worst * 1000:.1f} ms (cpu task {took * 1000:.0f} ms)")
if __name__ == "__main__":
test, mode = sys.argv[1:3]
{"cpu": cpu, "io": io, "race": race, "lag": lag}[test](mode)