Ruby 循环在线程中失败

发布于 2024-08-03 10:21:32 字数 608 浏览 4 评论 0原文

我在 Ruby 中有一个线程。它运行一个循环。当该循环达到睡眠(n)时,它会停止并且永远不会醒来。如果我在没有 sleep(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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

初见 2024-08-10 10:21:32

你缺少一个加入。

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文