Use mutex to lock : Mutex « Threads « Ruby






Use mutex to lock


$mutex = Mutex.new
t1 = Thread.new { $mutex.lock; sleep 30 }

sleep 1

t2 = Thread.new do
  if $mutex.try_lock
    puts "Locked it"
  else
    puts "Could not lock"   # Prints immediately
  end
end

sleep 2

 








Related examples in the same category

1.Classic deadlock: two threads and two locks