From: Kirk Haines Date: 2011-06-28T02:51:50+09:00 Subject: Re: Understanding Threading... On Mon, Jun 27, 2011 at 9:01 AM, Darryl L. Pierce wrote: > I'm working on a use case where I need to spawn a thread that handles a > blocking piece of communication and have it call back into a lamba > function when the call completes. All without blocking the main > application thread. > > The code I have is: > > class Foo > >  def sync(args = {}, &callback) >    block = args[:block] || false >    if block >      Thread.new do >        # passing in true says to block until the underlying code ends >        @underlying_impl.sync true >        callback.call >      end >    else >      @underlying_impl.sync false >      callback.call >    end >  end > > end > > What I _want_ to have happen is that, if I call this with :block => > true, the blocking call would get spawned off on a separate thread and > run in parallel to the main thread. And, of course, if called with > :block => false (or without :block at all) that the calling thread would > block until the sync exits. > > However, what I'm seeing is that, even with :block => true, the new > thread is created but the main thread is blocking. If I put a > Thread.pass call in just before calling @underlying_impl.sync then the > main thread updates but the other thread never executes. > > Am I misunderstanding Threading in Ruby? In Java spawning a Thread has > that other thread run in parallel without interaction. Does Ruby not > work the same way? The details of how threading in Ruby works really depends on the implementation of Ruby that you are using. In MRI Ruby < 1.9, threads were green threads, implemented with the Ruby process itself. CPU intensive code, and threads that invoke external C functions will not benefit from these threads (generally). In MRI Ruby 1.9.x, threads are real system threads. However, there is still a global interpreter lock that ensures that only one Ruby thread is running at a time. It is possible for a C extension to be running it's code at the same time that Ruby is executing, however, if the C extension is written to do that. In JRuby, threads are regular Java threads, and behave the same way. In Rubinius, threads are like 1.9.x threads, BUT Rubinius is removing the single global lock, so in the future, the production releases of Rubinius will have fully concurrent Ruby threads. Kirk Haines Software Engineer Engine Yard