在不影响输出的情况下,从Ruby中并行操作打印输出的最简单方法是什么? [英] What's the easiest way to print output from parallel operations in Ruby without jumbling up the output?
问题描述
说我分叉了一堆线程,并希望将每个线程的进度输出打印到STDERR.我该如何确保输出保持线原子性,即不会混淆同一条输出线中不同线程的输出?
Say I forked of a bunch of Threads and wants to print progress output from each one to STDERR. How can I do so in a way that ensures that the output retains line-atomicity, i.e. 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具有竞争条件,因为它可能会将换行符与行分开写入.您可能会在多线程应用程序中使用put来看到这种噪音:
puts has a race condition, since it may write the new-line separately from the line. You may see this sort of noise using puts in a multi-threaded application:
thread 0thread 1
thread 0thread 2
thread 1
thread 0thread 3
thread 2
thread 1
相反,使用print或printf
Instead, use print or printf
print "thread #{i}" + "\n"
print "thread #{i}\n"
printf "thread %d\n", i
或者,因为您要写STDERR:
Or, since you want to write to STDERR:
$stderr.print "thread #{i}\n"
这是Ruby中的错误吗?如果要以注释为标准,则不行.这是MRI 1.8.7至2.2.2的IO.put的定义:
Is it a bug in 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:
/*
* 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
*/
这篇关于在不影响输出的情况下,从Ruby中并行操作打印输出的最简单方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!