On Mon, Jun 27, 2011 at 9:01 AM, Darryl L. Pierce <mcpierce / gmail.com> wrot=
e:
> 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
>
> =A0def sync(args =3D {}, &callback)
> =A0 =A0block =3D args[:block] || false
> =A0 =A0if block
> =A0 =A0 =A0Thread.new do
> =A0 =A0 =A0 =A0# passing in true says to block until the underlying code =
ends
> =A0 =A0 =A0 =A0 / underlying_impl.sync true
> =A0 =A0 =A0 =A0callback.call
> =A0 =A0 =A0end
> =A0 =A0else
> =A0 =A0 =A0 / underlying_impl.sync false
> =A0 =A0 =A0callback.call
> =A0 =A0end
> =A0end
>
> end
>
> What I _want_ to have happen is that, if I call this with :block =3D>
> 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 =3D> false (or without :block at all) that the calling thread woul=
d
> block until the sync exits.
>
> However, what I'm seeing is that, even with :block =3D> 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