Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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}
like image 312
dan Avatar asked Feb 18 '11 17:02

dan


1 Answers

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

Instead, use print or printf

print "thread #{i}" + "\n"
print "thread #{i}\n"
printf "thread %d\n", i

Or, since you want to write to STDERR:

$stderr.print "thread #{i}\n"

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
 */
like image 160
Wayne Conrad Avatar answered Oct 20 '22 10:10

Wayne Conrad