为什么我会遇到僵局? 使用Thread,Queue和ActiveRecord。 Ruby 1.9.3,Rails 2.3.18

我通过运行多个线程并等待第一个线程以有效答案返回来缓解特定操作的低成功率。 我在下面创建了一个最小的示例:

THREADS = [] if !defined?(THREADS) def threadtest THREADS.clear queue, mutex, result = Queue.new, Mutex.new, nil 10.times do |i| THREADS << Thread.new do counted = (10e6 + rand(10e6)).to_i.times { } # randomize computation time num = rand(8) # succeed only 1/8 of the time #mutex.synchronize do # even if wrapped in mutex # print "#{User.last.inspect}\n" # deadlocks below if uncommented #end queue << [num, counted, i] end end 10.times do |i| result, counted, num = queue.pop # deadlocks here if result.zero? puts "#{i}: #{num} succeeds after #{counted} counts" break elsif num.present? puts "#{i}: #{num} failed with #{result} after #{counted} counts" end end THREADS.each(&:exit) return result end 30.times { threadtest } # deadlock happens on "high load" 

错误如下:

 fatal: deadlock detected from /usr/lib/ruby/1.9.1/thread.rb:189:in `sleep' from /usr/lib/ruby/1.9.1/thread.rb:189:in `block in pop' from :10:in `synchronize' from /usr/lib/ruby/1.9.1/thread.rb:184:in `pop' from (irb):38:in `block in threadtest' from (irb):37:in `times' from (irb):37:in `threadtest' from (irb):53:in `block in irb_binding' from (irb):53:in `times' from (irb):53 from /usr/local/bin/irb:12:in `' 

为了防止僵局,我尝试了很多变种,但都无济于事。 我可以详细说明我到目前为止所做的一些实验。 由于我的应用程序需要重构的数量,我确实有一个想法,我一直在避免。

是否只是通过多个线程无法访问ActiveRecord的情况?

我会想到它们时会更新一些细节。

rails中的’死锁检测’错误是我找到的最接近的相关问题,但它没有答案。

我有同样的错误,不得不添加

 gem 'net-ssh-gateway' 

在文件Gemfile.lock ,因为捆绑的版本不能与已安装的ruby一起使用。 似乎在较新的ruby版本中依赖性不再得到解决。