Ruby循环在线程中失败 [英] Ruby Loop Failing in Thread

查看:63
本文介绍了Ruby循环在线程中失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Ruby中有一个线程.它运行一个循环.当该循环达到sleep(n)时,它将停止并且永不唤醒.如果我在不使用sleep(n)的情况下运行循环,则它将作为无限循环运行.

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

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

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

推荐答案

您缺少联接.

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

这篇关于Ruby循环在线程中失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆