Locks and synchronization

suggest change

When several threads read and write the same objects, you need synchronization to keep the data consistent. Ruby's standard library gives you:

Tool Use it for
Thread::Mutex (Mutex) mutual exclusion: only one thread runs a critical section at a time
Monitor / MonitorMixin a re-entrant lock: the owning thread can lock it again
Thread::ConditionVariable waiting until some condition becomes true, with a Mutex
Thread::Queue / Thread::SizedQueue handing work between threads; synchronization is built in

The Race conditions article explains why the GVL does not make counter += 1 safe. This article covers the locking tools themselves and the patterns built on them.

Mutex basics

Mutex is an alias for Thread::Mutex. A mutex is either unlocked or held by exactly one thread (more precisely, by one fiber):

m = Mutex.new
p m.locked?    # not held by anyone
p m.lock       # returns the mutex itself
p m.locked?
p m.owned?     # held by the current thread?
p m.try_lock   # already locked: returns false instead of blocking
m.unlock
p m.try_lock   # free: acquires it and returns true
m.unlock
p Mutex.equal?(Thread::Mutex)
false
#<Thread::Mutex:0x0000025c7022bb08>
true
true
false
true
true

lock blocks until the mutex is free. try_lock never blocks, which is useful when you'd rather do something else than wait.

Always prefer synchronize

Calling lock and unlock by hand is fragile: an exception between them leaves the mutex locked forever. synchronize takes the lock, runs the block, releases the lock in an ensure, and returns the block's value:

m = Mutex.new
result = m.synchronize { 6 * 7 }
p result

begin
  m.synchronize { raise "boom" }
rescue => e
  puts "rescued #{e.message}, locked? #{m.locked?}"
end
42
rescued boom, locked? false

Mutex is not re-entrant

A thread that already holds a Mutex can't lock it again. Ruby detects this and raises ThreadError instead of hanging. Unlocking a mutex you don't own is also an error:

m = Mutex.new

begin
  m.synchronize { m.synchronize { } }
rescue ThreadError => e
  puts "ThreadError: #{e.message}"
end

begin
  m.unlock
rescue ThreadError => e
  puts "ThreadError: #{e.message}"
end

t = Thread.new { m.lock; sleep 0.1 }
sleep 0.05
begin
  m.unlock
rescue ThreadError => e
  puts "ThreadError: #{e.message}"
end
t.join
ThreadError: deadlock; recursive locking
ThreadError: Attempt to unlock a mutex which is not locked
ThreadError: Attempt to unlock a mutex which is locked by another thread/fiber

If methods that take the lock call each other, use a Monitor (see below).

Protecting an object's invariants

A lock protects more than a single variable. It makes a whole check-then-act sequence atomic. Here is a bank account without a lock. Every thread checks the balance, sees 100, and withdraws:

class UnsafeAccount
  attr_reader :balance

  def initialize(balance) = @balance = balance

  def withdraw(amount)
    return false if @balance < amount
    sleep 0.001 # simulate a slow check, e.g. a fraud service
    @balance -= amount
    true
  end
end

account = UnsafeAccount.new(100)
results = 10.times.map { Thread.new { account.withdraw(30) } }.map(&:value)
p results.count(true)
p account.balance
10
-200

Ten withdrawals of 30 went through on a balance of 100. If the check and the update happen under one lock, only three succeed:

class BankAccount
  attr_reader :balance

  def initialize(balance)
    @balance = balance
    @lock = Mutex.new
  end

  def withdraw(amount)
    @lock.synchronize do
      return false if @balance < amount
      sleep 0.001 # simulate a slow check, e.g. a fraud service
      @balance -= amount
      true
    end
  end
end

account = BankAccount.new(100)
results = 10.times.map { Thread.new { account.withdraw(30) } }.map(&:value)
p results.count(true)
p account.balance
3
10

return inside synchronize is fine: the lock is released on the way out.

Rules of thumb:

Monitor: a re-entrant lock

Monitor (from require "monitor") works like a Mutex, but the thread that owns it can lock it again. This lets public synchronized methods call each other:

require "monitor"

class Inventory
  def initialize
    @items = Hash.new(0)
    @lock = Monitor.new
  end

  def add(name, qty)
    @lock.synchronize { @items[name] += qty }
  end

  # calls add while already holding the lock: fine with Monitor
  def add_many(pairs)
    @lock.synchronize do
      pairs.each { |name, qty| add(name, qty) }
    end
  end

  def to_h = @lock.synchronize { @items.dup }
end

inv = Inventory.new
4.times.map { Thread.new { 1000.times { inv.add_many(apple: 1, pear: 2) } } }.each(&:join)
p inv.to_h
{apple: 4000, pear: 8000}

With a Mutex instead of a Monitor, add_many would raise ThreadError: deadlock; recursive locking.

to_h returns a copy (dup), not the internal hash. Returning the hash itself would let callers read it while another thread changes it.

MonitorMixin

MonitorMixin turns any object into a monitor, adding synchronize, mon_locked?, mon_owned?, new_cond and friends:

require "monitor"

class Registry
  include MonitorMixin

  def initialize
    super() # initializes the monitor; the () matters
    @entries = []
  end

  def register(x)
    synchronize { @entries << x unless include?(x) }
  end

  def include?(x)
    synchronize { @entries.include?(x) }
  end

  def size = synchronize { @entries.size }
end

r = Registry.new
8.times.map { |i| Thread.new { 100.times { |n| r.register(n % 50) } } }.each(&:join)
p r.size
p r.mon_locked?
50
false

Write super() with empty parentheses. A bare super passes along initialize's arguments. MonitorMixin#initialize forwards them up to BasicObject#initialize, which raises ArgumentError if there are any.

You can also add it to a single object with extend:

require "monitor"
s = "shared".dup
s.extend(MonitorMixin)
s.synchronize { s << " string" }
p s
"shared string"

Monitor is a bit slower than Mutex. Use Mutex by default and switch to Monitor when you need re-entrancy.

ConditionVariable: waiting for a condition

Sometimes a thread has to wait until another thread changes some state, for example until a config has loaded or until a buffer has room. Polling in a loop with sleep wastes CPU and adds latency. A ConditionVariable lets a thread sleep until it is woken:

Both waiting and signalling happen while holding the same mutex:

mutex = Mutex.new
ready = ConditionVariable.new
config = nil

workers = 3.times.map do |i|
  Thread.new do
    mutex.synchronize do
      ready.wait(mutex) while config.nil? # always re-check in a loop
      puts "worker #{i} sees #{config}"
    end
  end
end

sleep 0.1 # pretend loading takes a while
mutex.synchronize do
  config = { env: "prod" }
  ready.broadcast # wake every waiting thread
end
workers.each(&:join)
worker 0 sees {env: "prod"}
worker 2 sees {env: "prod"}
worker 1 sees {env: "prod"}

Always call wait in a while loop that re-checks the condition, never in a single if:

A bounded buffer

The classic example uses two condition variables, one for "not full" and one for "not empty":

class BoundedBuffer
  def initialize(capacity)
    @capacity = capacity
    @items = []
    @mutex = Mutex.new
    @not_full = ConditionVariable.new
    @not_empty = ConditionVariable.new
  end

  def push(item)
    @mutex.synchronize do
      @not_full.wait(@mutex) while @items.size >= @capacity
      @items << item
      @not_empty.signal
    end
  end

  def pop
    @mutex.synchronize do
      @not_empty.wait(@mutex) while @items.empty?
      item = @items.shift
      @not_full.signal
      item
    end
  end
end

buf = BoundedBuffer.new(2)
producer = Thread.new do
  5.times { |i| buf.push(i); puts "pushed #{i}" }
  buf.push(:done)
end
consumer = Thread.new do
  while (item = buf.pop) != :done
    puts "  popped #{item}"
    sleep 0.05 # slow consumer, producer must wait
  end
end
[producer, consumer].each(&:join)
pushed 0
pushed 1
  popped 0
pushed 2
  popped 1
pushed 3
  popped 2
pushed 4
  popped 3
  popped 4

The producer gets at most two items ahead of the slow consumer. In real code, use the built-in SizedQueue for this (see below). The pattern is still worth knowing for state that doesn't fit a queue.

Waiting with a timeout

cv.wait(mutex, seconds) gives up after seconds. It doesn't tell you whether it was signalled or timed out, so track a deadline yourself and re-check the condition:

mutex = Mutex.new
cv = ConditionVariable.new
done = false

started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
mutex.synchronize do
  deadline = started + 0.5
  until done
    remaining = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC)
    break if remaining <= 0
    cv.wait(mutex, remaining)
  end
end
elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - started
puts "done=#{done} after #{elapsed.round(1)}s"
done=false after 0.5s

Use CLOCK_MONOTONIC rather than Time.now for timeouts: it is not affected when the system clock is changed.

Condition variables on a Monitor

A monitor creates its own condition variables with new_cond. They add wait_while and wait_until, which contain the loop for you. Here is a countdown latch, where the main thread waits until three services report that they are up:

require "monitor"

class Latch
  def initialize(count)
    @count = count
    @mon = Monitor.new
    @zero = @mon.new_cond
  end

  def count_down
    @mon.synchronize do
      @count -= 1
      @zero.broadcast if @count.zero?
    end
  end

  def wait
    @mon.synchronize { @zero.wait_while { @count > 0 } }
  end
end

latch = Latch.new(3)
3.times do |i|
  Thread.new do
    sleep 0.05 * (i + 1)
    puts "service #{i} up"
    latch.count_down
  end
end
latch.wait
puts "all services up"
service 0 up
service 1 up
service 2 up
all services up

Queues: synchronization built in

Often the simplest design is not to share mutable state at all and to pass messages instead. Thread::Queue and Thread::SizedQueue handle all the locking internally. SizedQueue is the bounded buffer from above. push blocks when the queue is full, and after close a pop on the drained queue returns nil:

q = SizedQueue.new(2)

producer = Thread.new do
  5.times do |i|
    q.push(i) # blocks while the queue holds 2 items
    puts "pushed #{i} (size #{q.size})"
  end
  q.close # consumers get nil once it drains
end

consumer = Thread.new do
  while (item = q.pop)
    sleep 0.05
    puts "  got #{item}"
  end
end
[producer, consumer].each(&:join)
pushed 0 (size 1)
pushed 1 (size 2)
pushed 2 (size 2)
  got 0
pushed 3 (size 2)
  got 1
pushed 4 (size 2)
  got 2
  got 3
  got 4

See the Queue chapter for more queue patterns.

Timeouts instead of waiting forever

Blocking forever on a lock or a queue turns a bug into a hung process. Most blocking primitives take a timeout:

q = Thread::Queue.new
p q.pop(timeout: 0.2)       # nil after 0.2s, nothing arrived

sq = SizedQueue.new(1)
sq.push(:a)
p sq.push(:b, timeout: 0.2) # nil: still full after 0.2s

m = Mutex.new
m.synchronize do
  m.sleep(0.1)              # releases m while sleeping, re-acquires after
  p m.owned?
end
nil
nil
true

Mutex#lock has no timeout. Use try_lock in a loop if you need one (see the deadlock section below).

Deadlocks

A deadlock happens when two threads each hold a lock the other one needs. If every thread in the process ends up blocked, CRuby detects it and raises fatal in the main thread:

a = Mutex.new
b = Mutex.new

t1 = Thread.new { a.synchronize { sleep 0.1; b.synchronize { puts "t1 done" } } }
t2 = Thread.new { b.synchronize { sleep 0.1; a.synchronize { puts "t2 done" } } }

begin
  [t1, t2].each(&:join)
rescue Exception => e
  puts "#{e.class}: #{e.message.lines.first}"
end
fatal: No live threads left. Deadlock?

The full message lists every thread and what it is blocked on. Don't count on this check, though. If any thread is still alive (a web server's accept loop, a timer thread), the deadlocked threads just hang without any error.

Fix 1: always lock in the same order

If every thread takes locks in the same global order, a cycle can't form. A common trick is to sort by a stable id:

Account = Struct.new(:id, :balance, :lock)

def transfer(from, to, amount)
  first, second = [from, to].sort_by(&:id) # same order for every thread
  first.lock.synchronize do
    second.lock.synchronize do
      from.balance -= amount
      to.balance += amount
    end
  end
end

x = Account.new(1, 1000, Mutex.new)
y = Account.new(2, 1000, Mutex.new)
threads = 4.times.map do |i|
  Thread.new do
    500.times { i.even? ? transfer(x, y, 1) : transfer(y, x, 1) }
  end
end
threads.each(&:join)
p [x.balance, y.balance, x.balance + y.balance]
[1000, 1000, 2000]

Fix 2: try_lock and back off

When there is no natural order, take the first lock, try the second, and if that fails, release everything, sleep a random short time and retry:

def lock_both(a, b, attempts: 5)
  attempts.times do
    a.synchronize do
      if b.try_lock
        begin
          return yield
        ensure
          b.unlock
        end
      end
    end
    sleep rand * 0.01 # back off and retry
  end
  raise "could not acquire both locks"
end

a = Mutex.new
b = Mutex.new
holder = Thread.new { b.synchronize { sleep 0.02 } }
sleep 0.005
p lock_both(a, b) { :got_both }
holder.join
:got_both

The random sleep stops two threads from retrying in lockstep forever (a livelock).

The best fix is to hold only one lock at a time. Copy what you need, release, then take the next lock.

A read-write lock

A plain mutex serializes readers too. When reads are frequent, slow and rarely interrupted by writes, a read-write lock lets many readers in at once while a writer gets exclusive access. The standard library doesn't have one, but it is easy to build from a Mutex and a ConditionVariable:

class ReadWriteLock
  def initialize
    @mutex = Mutex.new
    @cond = ConditionVariable.new
    @readers = 0
    @writer = false
  end

  def read
    @mutex.synchronize do
      @cond.wait(@mutex) while @writer
      @readers += 1
    end
    begin
      yield
    ensure
      @mutex.synchronize do
        @readers -= 1
        @cond.broadcast if @readers.zero?
      end
    end
  end

  def write
    @mutex.synchronize do
      @cond.wait(@mutex) while @writer || @readers > 0
      @writer = true
    end
    begin
      yield
    ensure
      @mutex.synchronize do
        @writer = false
        @cond.broadcast
      end
    end
  end
end

lock = ReadWriteLock.new
data = { version: 0 }
max_concurrent = 0
active = 0
stats = Mutex.new

readers = 5.times.map do
  Thread.new do
    lock.read do
      stats.synchronize { active += 1; max_concurrent = [max_concurrent, active].max }
      sleep 0.05
      stats.synchronize { active -= 1 }
      data[:version]
    end
  end
end
writer = Thread.new { sleep 0.01; lock.write { data[:version] += 1 } }

p readers.map(&:value)
writer.join
p data
puts "max readers at once: #{max_concurrent}"
[0, 0, 0, 0, 0]
{version: 1}
max readers at once: 5

All five readers ran at the same time. The writer waited until they had finished. This simple version prefers readers, so a steady stream of readers can starve a writer. For production use, reach for a tested implementation such as the one in concurrent-ruby.

concurrent-ruby

The concurrent-ruby gem (gem install concurrent-ruby, used by Rails) provides tested higher-level primitives: atomics, read-write locks, latches, semaphores, thread pools and futures:

require "concurrent"

counter = Concurrent::AtomicFixnum.new(0)
10.times.map { Thread.new { 10_000.times { counter.increment } } }.each(&:join)
p counter.value

lock = Concurrent::ReentrantReadWriteLock.new
cache = {}
lock.with_write_lock { cache[:a] = 1 }
p lock.with_read_lock { cache[:a] }

ref = Concurrent::AtomicReference.new([])
4.times.map { |i| Thread.new { ref.update { |list| list + [i] } } }.each(&:join)
p ref.get.sort
100000
1
[0, 1, 2, 3]

AtomicReference#update uses compare-and-set: it re-runs the block if another thread changed the value in the meantime, so the block must have no side effects. Other useful classes are Concurrent::CountDownLatch, Concurrent::Semaphore, Concurrent::Map (a thread-safe hash) and Concurrent::Array.

Thread-safe lazy initialization

@x ||= compute is not atomic. Two threads can both see nil and both compute. When the computation is expensive or must happen only once, wrap it in a lock:

class Config
  @lock = Mutex.new

  def self.instance
    return @instance if @instance # fast path, no lock once initialized
    @lock.synchronize do
      @instance ||= begin
        puts "loading config (once)"
        sleep 0.05
        { debug: false }
      end
    end
  end
end

5.times.map { Thread.new { Config.instance } }.each(&:join)
p Config.instance
loading config (once)
{debug: false}

The ||= inside the lock is the real check. The unlocked fast path just avoids taking the lock on every call. This relies on CRuby publishing an instance variable assignment atomically. To be safe on every implementation, drop the fast path, or initialize eagerly when the class loads.

Mutexes belong to fibers

Since Ruby 3.0 a mutex is owned by a fiber, not by a thread. Another fiber on the same thread can't take a mutex that one fiber holds:

m = Mutex.new
f = Fiber.new { m.lock; Fiber.yield; m.unlock }
f.resume    # the fiber now owns the mutex
p m.locked?
p m.owned?   # false: the main fiber is not the owner
p m.try_lock # false: another fiber of the same thread can't take it
f.resume     # the fiber unlocks
p m.locked?
true
false
false
false

With a fiber scheduler (see Fibers and Async), a fiber that blocks on Mutex#lock yields to other fibers instead of blocking the whole thread.

Mutexes and monitors can't be used inside a Signal.trap handler (ThreadError: can't be called from trap context). The Signals and graceful shutdown article shows how to hand signals to a regular thread.

Choosing a tool

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents