死锁导致异常

时间:2014-07-20 17:22:45

标签: ruby-on-rails ruby multithreading thread-safety

我有以下主题:

require 'thread'

myqueue = Queue.new

Thread.new do
  loop do
    a = Users.find(id)
    myqueue << a
  end
end

loop do
  user = myqueue.pop
  puts user.class
end

由于未加载用户而导致死锁。我如何捕获/拯救此类异常?

1 个答案:

答案 0 :(得分:0)

找到了解决方案!

你必须将救援包裹在循环中:

require 'thread'

myqueue = Queue.new

Thread.new do
  loop do
    begin
      a = Users.find(id)
      myqueue << a
    rescue Exception => e
      puts e.message
    end
  end
end

loop do
  user = myqueue.pop
  puts user.class
end