Race conditions
suggest changeA race condition occurs when multiple concurrent threads access and mutate shared data simultaneously, and the outcome depends on the non-deterministic order of thread execution and CPU scheduling.
The Global VM Lock (GVL) Myth
A common misconception in Ruby (specifically CRuby / MRI) is that the Global VM Lock (GVL) makes multi-threaded code safe from race conditions. While the GVL ensures only one thread executes Ruby virtual machine bytecodes at any given instant, compound operations in Ruby are not atomic.
For example, counter += 1 consists of three distinct bytecode steps:
- Read
counter - Add
1 - Write back to
counter
The Ruby runtime can switch thread execution between any of these steps.
Reproducing a Race Condition
In current CRuby a plain counter += 1 on a local variable rarely loses updates in practice, because the GVL only switches threads at specific points (method calls, block returns, loop iterations). That is an implementation detail, not a guarantee. To make the race visible, the example below splits the steps and calls Thread.pass between the read and the write, which is exactly what happens when the scheduler preempts a thread there:
counter = 0
threads = []
10.times do
threads << Thread.new do
10_000.times do
# Non-atomic read-modify-write
current = counter # 1. read
Thread.pass # another thread runs here
counter = current + 1 # 2. add, 3. write back
end
end
end
threads.each(&:join)
# Expected: 100_000
# Actual result is much lower (e.g. 10_058) due to lost updates
puts "Final counter: #{counter}"
Solution 1: Thread::Mutex
A Mutex (Mutual Exclusion lock) ensures that only one thread can execute a critical section of code at a time:
counter = 0
mutex = Thread::Mutex.new
threads = []
10.times do
threads << Thread.new do
10_000.times do
# synchronize automatically acquires and safely releases the lock
mutex.synchronize do
counter += 1
end
end
end
end
threads.each(&:join)
puts "Safe counter: #{counter}" # 100_000
mutex.synchronize ensures that the lock is released even if an exception is raised within the block.
Solution 2: Thread::Queue
Instead of sharing state and protecting it with locks, use Thread::Queue to pass data between threads. Thread::Queue is inherently thread-safe and non-blocking for producers:
queue = Thread::Queue.new
# Producer threads
producers = 3.times.map do |i|
Thread.new do
5.times do |n|
queue << "Task-#{i}-#{n}"
end
end
end
# Consumer thread
consumer = Thread.new do
15.times do
task = queue.pop # Blocks safely until an item is available
puts "Processed: #{task}"
end
end
producers.each(&:join)
consumer.join
Solution 3: Thread-Local Storage
If threads require their own private copy of state without sharing, store state in Thread.current:
threads = 5.times.map do |i|
Thread.new do
Thread.current[:request_id] = "req-#{i}-#{rand(1000)}"
# Do work safely without conflicting with other threads
puts "Thread #{i} working on #{Thread.current[:request_id]}"
end
end
threads.each(&:join)
Solution 4: Ractors (Ruby 3+)
Ruby 3 introduced Ractors (Ruby's implementation of the Actor Model), which provide true parallel execution across multiple CPU cores without shared mutable state:
# Ractors communicate solely via message passing
r = Ractor.new do
count = 0
loop do
msg = Ractor.receive
break if msg == :stop
count += msg
end
count
end
r.send(10)
r.send(20)
r.send(:stop)
puts "Ractor total: #{r.value}" # 30 (Ruby 3.5+; use r.take on older versions)