[英]What's the easiest way to print output from parallel operations in Ruby without jumbling up the output?
Say I forked of a bunch of Threads and wants to print progress output from each one to STDERR. 假设我分叉了一堆线程,并希望将每个进程输出打印到STDERR。 How can I do so in a way that ensures that the output retains line-atomicity, ie doesn't jumble up output from different threads in the same output line?
我怎样才能确保输出保持行原子性,即不会混淆同一输出行中不同线程的输出?
# run this a few times and you'll see the problem
threads = []
10.times do
threads << Thread.new do
puts "hello" * 40
end
end
threads.each {|t| t.join}
puts has a race condition, since it may write the new-line separately from the line. puts有一个竞争条件,因为它可以单独写一行换行。 You may see this sort of noise using puts in a multi-threaded application:
您可以在多线程应用程序中使用puts来看到这种噪音:
thread 0thread 1
thread 0thread 2
thread 1
thread 0thread 3
thread 2
thread 1
Instead, use print or printf 相反,使用print或printf
print "thread #{i}" + "\n"
print "thread #{i}\n"
printf "thread %d\n", i
Or, since you want to write to STDERR: 或者,因为您要写入STDERR:
$stderr.print "thread #{i}\n"
Is it a bug in Ruby? 这是Ruby中的错误吗? Not if the comments are to be taken as the standard.
如果要将评论作为标准,则不是。 Here's the definition of IO.puts from MRI 1.8.7 though 2.2.2:
这是从MRI 1.8.7到2.2.2的IO.puts的定义:
/*
* call-seq:
* ios.puts(obj, ...) => nil
*
* Writes the given objects to <em>ios</em> as with
* <code>IO#print</code>. Writes a record separator (typically a
* newline) after any that do not already end with a newline sequence.
* If called with an array argument, writes each element on a new line.
* If called without arguments, outputs a single record separator.
*
* $stdout.puts("this", "is", "a", "test")
*
* <em>produces:</em>
*
* this
* is
* a
* test
*/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.