为什么这段代码会打印相同的内容两次?
我正在尝试编写一些小的超时代码:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Ruby 在 io 缓冲和线程方面存在一个错误,看起来与此完全相同。最近已经修复了,所以升级一下。
Ruby had a bug with io buffering and threading that looks exactly like this. It has been fixed recently, so upgrade.
这对我来说听起来就像“嗨!”被缓冲和刷新两次,一次由执行
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 onstdout
, or else to usewrite
to fd 1, bypassing stdio. Presumably Ruby has an equivalent at least of the first of these options?