Is autoload thread-safe in Ruby 1.9?

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:

  • http://redmine.ruby-lang.org/issues/921
  • http://jira.codehaus.org/browse/JRUBY-3194

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.