Ruby Loop Failing in Thread

江枫思渺然 提交于 2020-01-07 07:14:08

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/1347853/ruby-loop-failing-in-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!