Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is autoload thread-safe in Ruby 1.9?

It seems to me that the Ruby community has been freaking out a little about autoload since this famous thread, discouraging its use for thread safety reasons.

Does anyone know if this is no longer an issue in Ruby 1.9.1 or 1.9.2? I've seen a bit of talk about wrapping requires in mutexes and such, but the 1.9 changelogs (or at least as much as I've been able to find) don't seem to address this particular question. I'd like to know if I can reasonably start autoloading in 1.9-only libraries without any reasonable grief.

Thanks in advance for any insights.

like image 634
SFEley Avatar asked May 14 '10 22:05

SFEley


People also ask

Is Ruby set thread-safe?

None of the core data structures (except for Queue) in Ruby are thread-safe. The structures are mutable, and when shared between threads, there are no guarantees the threads won't overwrite each others' changes. Fortunately, this is rarely the case in Rails apps.

Are Ruby hashes thread-safe?

No, you cannot rely on Hashes being thread safe, because they aren't built to be thread safe, most probably for performance reasons. In order to overcome these limitations of the standard library, Gems have been created which provide thread safe (thread_safe) or immutable (hamster) data structures.


1 Answers

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.

like image 82
Denis de Bernardy Avatar answered Oct 19 '22 16:10

Denis de Bernardy