From: Luiz Angelo Daros de Luca Date: 2011-06-28T02:28:07+09:00 Subject: Re: Understanding Threading... Hello Darry, Is your block using some C extension? In ruby<1.9, threads in ruby do not use system threads. So, if you call some external C command, no thread will run in ruby. In ruby>=1.9, it uses pthreads. Even though, threads in ruby does not run in parallel. There is a global mutex that makes every thread runs isolated. Just like a single processor machine. In the past, while programming with Qt in Ruby, I did a simple hack in order to get ruby some processor time when main thread goes loop. block=Proc.new{ Thread.pass } timer=Qt::Timer.new(window) invoke=Qt::BlockInvocation.new(timer, block, "invoke()") Qt::Object.connect(timer, SIGNAL("timeout()"), invoke, SLOT("invoke()")) timer.start(10) Regards, ---      Luiz Angelo Daros de Luca, Me.             luizluca@gmail.com 2011/6/27 Darryl L. Pierce : > 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? > > -- > Darryl L. Pierce > http://mcpierce.multiply.com/ > "What do you care what people think, Mr. Feynman?" >