Ruby Loop Failing in Thread

loopsrubysleepwindows-xp

I have a thread in Ruby. It runs a loop. When that loop reaches a sleep(n) it halts and never wakes up. If I run the loop with out sleep(n) it runs as a infinite loop.

Whats going on in the code to stop the thread from running as expected?
How do i fix it?

class NewObject
    def initialize
        @a_local_var = 'somaText'
    end

    def my_funk(a_word)
        t = Thread.new(a_word) do |args|
            until false do
                puts a_word
                puts @a_local_var
                sleep 5 #This invokes the Fail
            end
        end
    end
end

if __FILE__ == $0
    s = NewObject.new()
    s.my_funk('theWord')
    d = gets
end

My platform is Windows XP SP3
The version of ruby I have installed is 1.8.6

Best Answer

You're missing a join.

class NewObject
  def initialize
    @a_local_var = 'somaText'
  end

  def my_funk(a_word)
    t = Thread.new(a_word) do |args|
      until false do
        puts a_word
        puts @a_local_var
        sleep 5 
      end
    end
    t.join # allow this thread to finish before finishing main thread
  end
end

if __FILE__ == $0
  s = NewObject.new()
  s.my_funk('theWord')
  d = gets # now we never get here
end