Why does this code print the same thing twice?
I am trying to write some small timeout code:
t = Thread.new { sleep 3 } # <- The thread that will do s开发者_C百科tuff.
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?
Ruby had a bug with io buffering and threading that looks exactly like this. It has been fixed recently, so upgrade.
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?
精彩评论