为什么我陷入僵局?使用线程,队列和ActiveRecord. Ruby 1.9.3,Rails 2.3.18 [英] Why am I getting deadlocks? Using Thread, Queue, and ActiveRecord. Ruby 1.9.3, Rails 2.3.18
问题描述
我通过运行多个线程并等待第一个线程返回有效答案来缓解特定操作的低成功率.我在下面创建了一个最小的示例:
I mitigate the low success rate of a particular operation by running multiple threads and waiting for the first one to return with a valid answer. I've created a minimal example below:
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 <internal:prelude>: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 `<main>'
为了防止死锁,我尝试了许多变种,但都无济于事.如果需要,我可以详细介绍到目前为止我已经做过的一些实验.我确实有另外一个想法,由于在应用程序中需要进行大量的重构,因此我一直在避免这样做.
I've tried many variations in an attempt to prevent the deadlock, all to no avail. I can detail some of the experimentations I've done so far if requested. I do have one more idea that I've been avoiding due to the amount of refactoring it'd require in my application.
是否只能通过多个线程访问ActiveRecord?
Is it simply the case that ActiveRecord can't be accessed via multiple threads?
我会根据自己的想法更新一些细节.
I'll update with a few more details as I think of them.
rails中的死锁检测"错误是我发现的最接近的相关问题,但没有答案.
'deadlock detected' error in rails is the the closest related question I found, but it's got no answers.
推荐答案
我遇到了相同的错误,不得不添加
I had the same error and had to add the
gem 'net-ssh-gateway'
文件Gemfile.lock
中的
,因为捆绑的版本不适用于已安装的ruby.似乎在新的ruby版本中不再解决依赖关系.
in the file Gemfile.lock
, because the version that was bundled didn't work with the installed ruby. Seems like the dependency wasn't resolved any more in the newer ruby version.
这篇关于为什么我陷入僵局?使用线程,队列和ActiveRecord. Ruby 1.9.3,Rails 2.3.18的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!