Jos*_*ehl 6 ruby activesupport thread-safety ruby-on-rails-4
代码:
threads = []
Thread.abort_on_exception=true
begin # throw exceptions in threads so we can see them
threads << Thread.new{@a = MyClass.m1}
threads << Thread.new{@b = MyClass.m2}
threads << Thread.new{@c = MyClass.m3}
threads.each { |thr| thr.join }
rescue Exception => e
puts "EXCEPTION: #{e.inspect}"
puts "MESSAGE: #{e.message}"
end
Run Code Online (Sandbox Code Playgroud)
碰撞:
.rvm/gems/ruby-2.1.3@req/gems/activesupport-4.1.5/lib/active_support/dependencies.rb:478:in load_missing_constant': Circular dependency detected while autoloading constant MyClass
挖掘一下之后,似乎由于每个Thread都引用了MyClass,因此导致ruby自动加载时出错.如果我MyClass在进行线程调用之前添加一行引用,似乎可以防止错误.
我的问题是,是否有一种"正确"的方法来防止这种情况发生,或者它是红宝石中的一些错误?根据http://blog.plataformatec.com.br/2012/08/eager-loading-for-greater-good/,我的理解是自动加载是线程安全的.
Ruby 曾经在这方面有过问题Threaded autoload,甚至require在这方面也有问题。ruby 2.0在 ruby-lang.org 上查看此错误时已修复它。
Rails 可能仍然存在 bug [Circular dependency error with lib classes](Circular dependency error with lib classes)
无论如何,修复方法都是在将符号放入线程之前简单地要求或引用该符号。
require 'myclass'
Run Code Online (Sandbox Code Playgroud)
或者
defined? MyClass
Run Code Online (Sandbox Code Playgroud)