multithreading - What's the easiest way to print output from parallel operations in Ruby without jumbling up the output? -
say forked of bunch of threads , wants print progress output each 1 stderr. how can in way ensures output retains line-atomicity, i.e. doesn't jumble output different threads in same output line?
# run few times , you'll see problem threads = [] 10.times threads << thread.new puts "hello" * 40 end end threads.each {|t| t.join}
puts has race condition, since may write new-line separately line. may see sort of noise using puts in 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",
or, since want write stderr:
$stderr.print "thread #{i}\n"
is bug in ruby? not if comments taken standard. here's definition of io.puts mri 1.8.7 though 2.2.2:
/* * call-seq: * ios.puts(obj, ...) => nil * * writes given objects <em>ios</em> * <code>io#print</code>. writes record separator (typically * newline) after not end newline sequence. * if called array argument, writes each element on new line. * if called without arguments, outputs single record separator. * * $stdout.puts("this", "is", "a", "test") * * <em>produces:</em> * * * * * test */
Comments
Post a Comment