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 lockGVL (Global VM Lock)GIL (Global Interpreter Lock)
Time slice before a CPU-bound thread is preempted100 ms (TIME_QUANTUM_MSEC)5 ms (sys.getswitchinterval(), settable)
Released onblocking I/O, sleep, Queue#pop, C code calling rb_thread_call_without_gvlblocking I/O, time.sleep, C code using Py_BEGIN_ALLOW_THREADS (NumPy, hashlib, zlib)
Lightweight tasksFiber + Fiber::Scheduler (the async gem): existing Net::HTTP, sleep, sockets become non-blockingasyncio coroutines: needs async def/await and async libraries
Many threads, few OS threadsM:N threads (RUBY_MN_THREADS=1, 3.3+)—
Parallel interpreter code in one processRactor (experimental): one GVL eachsubinterpreters (3.14, concurrent.interpreters): one GIL each · free-threaded build (python3.14t): no GIL
Parallel processesfork, Puma workers, Sidekiq processesmultiprocessing, ProcessPoolExecutor (forkserver by default on Linux since 3.14), gunicorn workers

The two locks

Ruby hands the GVL over every 100 ms, Python hands the GIL over every 5 ms Ruby (MRI): the GVL changes hands every 100 ms thread A · CPU runs queued thread B · CPU queued runs thread C · I/O I/O ready, waits for the GVL next I/O 100 ms time slice: only now does C get the GVL 0 ms 50 ms 100 ms 150 ms 200 ms Python (GIL build): the GIL changes hands every 5 ms thread A · CPU thread B · CPU thread C · I/O I/O next I/O C waits at most one 5 ms switch interval 0 ms 50 ms 100 ms 150 ms 200 ms
Schematic of the lag test below, same 200 ms window. A thread that becomes ready waits for the current holder's time slice: up to 100 ms in Ruby (measured: 100.6 ms), up to 5 ms in Python (measured: 5.2 ms).
Ruby hands the GVL over every 100 ms, Python hands the GIL over every 5 ms Ruby: GVL every 100 ms thread A · CPU runs queued thread B · CPU queued runs thread C · I/O waits 100 ms: C runs 0 ms 50 ms 100 ms 150 ms 200 ms Python: GIL every 5 ms thread A · CPU thread B · CPU thread C · I/O C waits ≤ 5 ms 0 ms 50 ms 100 ms 150 ms 200 ms
Schematic of the lag test below, same 200 ms window. A thread that becomes ready waits for the current holder's time slice: up to 100 ms in Ruby (measured: 100.6 ms), up to 5 ms in Python (measured: 5.2 ms).

Beyond the lock

Ruby

Python

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.

Measured: Ruby with YJIT is 8× faster per core; both need processes, Ractors, subinterpreters or the free-threaded build to use 4 cores CPU-bound: 4 × fib(35) on 4 cores Ruby · sequential 0.278 s Ruby · 4 threads 0.271 s Ruby · 4 Ractors 0.080 s Ruby · 4 processes (fork) 0.073 s Python · sequential 2.233 s Python · 4 threads (GIL) 2.442 s Python · 4 processes 0.703 s Python · 4 subinterpreters 0.689 s Python · free-threaded: sequential 2.011 s Python · free-threaded: 4 threads 0.549 s 0 s 0.5 s 1 s 1.5 s 2 s 2.5 s I/O-bound: 10,000 concurrent 100 ms waits · wall time · RSS Ruby · 10,000 threads 1.092 s · 192 MB Ruby · 10,000 threads, M:N 0.335 s · 147 MB Ruby · 10,000 fibers (async) 0.360 s · 133 MB Python · 10,000 asyncio tasks 0.143 s · 34 MB Python · 10,000 threads 0.396 s · 60 MB Python · free-threaded: 10,000 threads 1.185 s · 275 MB 0 s 0.4 s 0.8 s 1.2 s ideal 0.100 s
Medians of rounds 2–4, Ruby 4.0.9 + YJIT and CPython 3.14.10 (GIL and free-threaded builds), each pinned to the same 4 cores. Dark bars Ruby, light bars Python.
Measured: Ruby with YJIT is 8× faster per core; both need processes, Ractors, subinterpreters or the free-threaded build to use 4 cores CPU: 4 × fib(35), 4 cores wall time, shorter is better Ruby · sequential 0.278 s Ruby · 4 threads 0.271 s Ruby · 4 Ractors 0.080 s Ruby · 4 processes (fork) 0.073 s Python · sequential 2.233 s Python · 4 threads (GIL) 2.442 s Python · 4 processes 0.703 s Python · 4 subinterpreters 0.689 s Python · free-threaded: sequential 2.011 s Python · free-threaded: 4 threads 0.549 s I/O: 10,000 × 100 ms waits wall time · resident memory Ruby · 10,000 threads 1.092 s · 192 MB Ruby · 10,000 threads, M:N 0.335 s · 147 MB Ruby · 10,000 fibers (async) 0.360 s · 133 MB Python · 10,000 asyncio tasks 0.143 s · 34 MB Python · 10,000 threads 0.396 s · 60 MB Python · free-threaded: 10,000 threads 1.185 s · 275 MB dashed amber tick: ideal 0.100 s
Medians of rounds 2–4, Ruby 4.0.9 + YJIT and CPython 3.14.10 on the same 4 cores. Dark bars Ruby, light bars Python.

1. CPU-bound: 4 × fib(35)

Rubywallspeed-upPythonwallspeed-up
sequential0.278 s1.0×sequential2.233 s1.0×
4 threads0.271 s1.0×4 threads (GIL build)2.442 s0.91×
4 Ractors0.080 s3.5×4 subinterpreters0.689 s3.2×
4 processes (fork)0.073 s3.8×4 processes (ProcessPoolExecutor)0.703 s3.2×
free-threaded: sequential2.011 s1.0×
free-threaded: 4 threads0.549 s3.7×

2. I/O-bound: 10,000 concurrent 100 ms waits

Runtime · primitivewallover the 0.100 s idealRSS
Python · 10,000 asyncio tasks0.143 s+43 ms34 MB
Ruby · 10,000 threads, M:N (RUBY_MN_THREADS=1)0.335 s+235 ms147 MB
Ruby · 10,000 fibers (async 2.46)0.360 s+260 ms133 MB
Python · 10,000 threads (GIL build)0.396 s+296 ms60 MB
Ruby · 10,000 threads (default 1:1)1.092 s+992 ms192 MB
Python free-threaded · 10,000 threads1.185 s+1,085 ms275 MB

3. Shared counter: 4 × 1,000,000 increments

CodeResult (expected 4,000,000)
Ruby · 4 threads · c += 14,000,000 (3 / 3 runs)
Ruby · v = c; Thread.pass; c = v + 11,000,000 (3 / 3)
Ruby · same, inside Mutex#synchronize4,000,000
Python GIL build · 4 threads · c += 14,000,000 (3 / 3)
Python GIL build · v = c; time.sleep(0); c = v + 11,000,000 (1,000,000 – 1,000,003)
Python GIL build · same, inside with lock:4,000,000
Python free-threaded · 4 threads · c += 13,252,428 (3,250,418 – 3,343,234)
Python · 4 asyncio tasks · v = c; await asyncio.sleep(0); c = v + 11,000,000 (3 / 3)

4. A blocked timer: 10 ms ticker next to a CPU-bound thread

Runtime · where the CPU work runsCPU taskworst ticker lateness
Ruby · another Thread, fib(37)177 ms100.6 ms
Ruby · a Ractor, fib(37)184 ms0.4 ms
Python GIL build · another thread, fib(32)173 ms5.2 ms
Python free-threaded · another thread, fib(32)120 ms0.2 ms
Python · a process, fib(32)231 ms3.2 ms
Python · on the asyncio loop, fib(32)136 ms135.7 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

RubyPython
A CPU-heavy thread (rendering, JSON, image work) delays every other thread by up to 100 msFour 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 childfork 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 ensureA sync library call inside a coroutine blocks the whole event loop

Which one for what

WorkloadRubyPython
Request/response web app, DB-boundPuma: threads × processesgunicorn/uvicorn: workers × threads or asyncio
10,000+ idle connectionsfibers (async, Falcon) or M:N threadsasyncio
CPU work in Ruby/Python codefork/Sidekiq processes, Ractorsprocesses, subinterpreters, the free-threaded build
Numeric worka native extension or another serviceNumPy and friends release the GIL inside C

Method

SetupDetails
Ruby4.0.9, image ruby:4.0, --yjit; async 2.46.0
Python3.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)
CPUAMD Ryzen AI Max+ 395, 4 cores (docker --cpuset-cpus=8-11), host not isolated
Runs4 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)

Questions? Let's Chat :)

concurrency