Ruby 在线程循环中休眠

发布于 2024-09-27 16:16:03 字数 580 浏览 1 评论 0原文

一年前我在这里发布了完全相同的问题: Ruby 循环在线程中失败

这里是代码(与上面的主题几乎相同) )

 class NewObject
    def my_funk
        t = Thread.new {
            until false do
                puts sleep 15 # sleeps way too much
            end
        }
        t.join
  end
end

if __FILE__ == $0
    s = NewObject.new()
    s.my_funk
end

这是输出:

15
42
36
38
33
45
42
33
32
40

该代码基本上打印实际睡眠的秒数。 有谁知道这里发生了什么以及如何解决它?

我运行的是 Windows 7 和 Ruby 1.8.7

I have the exact same problem posted here a year ago:
Ruby Loop Failing in Thread

Here the code (pretty much the same as in the topic above)

 class NewObject
    def my_funk
        t = Thread.new {
            until false do
                puts sleep 15 # sleeps way too much
            end
        }
        t.join
  end
end

if __FILE__ == $0
    s = NewObject.new()
    s.my_funk
end

And here is the output:

15
42
36
38
33
45
42
33
32
40

The code basically prints the actual number of seconds slept.
Does anyone know what's going on here and how to fix it?

I'm running Windows 7 and Ruby 1.8.7

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

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

发布评论

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

评论(1

久光 2024-10-04 16:16:03

如果我没记错的话,睡眠是使用本机系统调用实现的,并且可能会干扰由虚拟机管理的 ruby​​ green 线程。这也可以解释为什么 JRuby 和 1.9 不会遇到同样的问题......

If I'm not mistaken, sleep is implemented using the native system call and probably interferes with ruby green threads which are managed by the VM. This would also explain why JRuby and 1.9 do not suffer from the same problem....

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