Ruby循环失败

时间:2009-08-28 15:46:19

标签: ruby windows-xp loops sleep

我在Ruby中有一个帖子。它运行一个循环。当该循环达到睡眠时(n)它停止并且从不醒来。如果我在没有睡眠的情况下运行循环(n),它将作为无限循环运行。

代码中是怎么回事以阻止线程按预期运行? 我该如何解决?

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

我的平台是Windows XP SP3
我安装的ruby版本是1.8.6

1 个答案:

答案 0 :(得分:1)

你错过了一个加入。

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