ThreadError
RubyERRORNotableConcurrency

Invalid Thread or Mutex operation

Quick Answer

Use Mutex#synchronize (block form) instead of explicit lock/unlock to avoid ownership errors.

What this means

Raised for invalid operations on threads, mutexes, and related concurrency primitives. Common causes include unlocking a mutex you do not own, or joining a thread that would cause a deadlock.

Why it happens
  1. 1Calling Mutex#unlock from a thread that does not hold the lock
  2. 2Calling Thread#join on the current thread (self-join deadlock)
  3. 3Re-locking a non-reentrant mutex from the same thread

Fix

Use synchronize block form

Use synchronize block form
mutex = Mutex.new
mutex.synchronize do
  # critical section
  shared_resource.update
end
# mutex is automatically released even if an exception is raised

Why this works

synchronize guarantees the mutex is released at block exit, preventing deadlocks and ThreadError from manual unlock.

Code examples
Unlocking from wrong threadruby
m = Mutex.new
m.lock
Thread.new { m.unlock }.join
# ThreadError: Attempt to unlock a mutex which is locked by another thread
Safe synchronize patternruby
mutex.synchronize { counter += 1 }
Rescue ThreadErrorruby
begin
  mutex.unlock
rescue ThreadError => e
  puts "Mutex error: #{e.message}"
end
Sources
Official documentation ↗

Ruby Core Documentation

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Ruby errors