为什么这段代码会打印相同的内容两次?

发布于 2024-09-10 02:25:33 字数 382 浏览 0 评论 0原文

我正在尝试编写一些小的超时代码:

t = Thread.new { sleep 3 } # <- The thread that will do stuff.
Thread.new { sleep 2; t.kill; p 'hi!' } # <- The thread that will kill it after two seconds.
t.join

如果第一个线程在两秒内完成其工作,它将停止,主线程将无事可做。这将导致程序在第二个线程到达 t.kill 部分之前退出。但是,当我运行此代码时,“hi!” 会打印两次。将 p 替换为 puts 即可修复该问题。为什么会出现这种情况?

I am trying to write some small timeout code:

t = Thread.new { sleep 3 } # <- The thread that will do stuff.
Thread.new { sleep 2; t.kill; p 'hi!' } # <- The thread that will kill it after two seconds.
t.join

If the first thread completes it's job within two seconds, it will stop, and the main thread will have nothing to do. This will cause the program to exit before the second thread gets to the t.kill part. But, when I run this code, "hi!" gets printed out twice. Replacing the p with puts fixes it. Why does this happen?

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

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

发布评论

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

评论(2

允世 2024-09-17 02:25:33

Ruby 在 io 缓冲和线程方面存在一个错误,看起来与此完全相同。最近已经修复了,所以升级一下。

Ruby had a bug with io buffering and threading that looks exactly like this. It has been fixed recently, so upgrade.

淡忘如思 2024-09-17 02:25:33

这对我来说听起来就像“嗨!”被缓冲和刷新两次,一次由执行 p 操作的匿名线程执行,一次由主线程执行。如果这是一个 C 程序,修复它的方法是禁用 stdout 上的缓冲,或者使用 write 绕过 stdio 来写入 fd 1。想必 Ruby 至少有第一个选项的等效项?

This sounds to me like "hi!" is getting buffered up and flushed twice, once by the anonymous thread that did the p operation, and once by the main thread. If this were a C program, the way to fix it would be to disable buffering on stdout, or else to use write to fd 1, bypassing stdio. Presumably Ruby has an equivalent at least of the first of these options?

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