Is autoload thread-safe in Ruby 1.9?

痴心易碎 提交于 2019-12-02 22:00:00

I don't know about the general case, but repro example from that thread doesn't break in 1.9.1:

autoloaded.rb:

sleep 1
Bar::Foo = 1

autoloader.rb:

module Bar
   autoload :Foo, 'autoloaded.rb'
end

t1 = Thread.new { Bar::Foo }
t2 = Thread.new { Bar::Foo }
t1.join; t2.join

Bringing a 2011 update to this, since I was curious about it too.

Two tickets are currently opened:

The core devs suggest that require and autoload work in the same manner and are thread safe, in CRuby/JRuby 1.9. This, in the sense that ruby keeps a lock until the file is fully loaded.

This has the inconvenient side-effect of introducing potential deadlocks, however. Specifically:

  1. Th1 load A and locks it
  2. Th2 load B and locks it
  3. Th1 tries to load B as part of loading A, starts waiting for Th2
  4. Th2 tries to load A as part of loading B, starts waiting for Th1
  5. Deadlock...

The conclusion probably is: require everything you need before starting a thread if there's any potential for deadlock in your app.

raggi

it's always broken.

subload allows you to switch modes when in a threaded environment.

I use autoload still in threaded environment, but only during a single threaded boot sequence. I don't see any good reason to have a multithreaded startup process in a real world application. If you do have one, you will likely need to queue up actions for loading shared libraries as you will always have thread safety issues with class and instance level setup, most partuclarly with things like:

class Lib
  extend SomeClassFuncs
  do_something_with_class_funcs
end

This code is not thread safe a load time, irrespective of the loader.

If you can't see this, you shouldn't be threading.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!