views:

215

answers:

2

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

A: 

I just ran this with Ruby 1.8.7 on Linux(Ubuntu) and it behaved as expected (outputting two lines of text every 5 seconds until )

My suspicion therefore immediately jumps to a platform issue, particularly because threads are involved. Could you add what platform you are on and what version of Ruby you are using?

John F. Miller
I'm on windows xp sp3 and i just tried the code on another (xp sp3) machine with the same results i had before. Any known issues with Threads in Ruby on Windows?
JustSmith
+1  A: 

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
Sarah Mei
So what your saying is that my_funk would finish and then that would kill the scope that the thread var existed in so that it would stop executing? Cause with your suggestion it works.
JustSmith