This post originated from an RSS feed registered with Ruby Buzz
by Eric Hodel.
Original Post: Setting $stdout per-thread
Feed Title: Segment7
Feed URL: http://blog.segment7.net/articles.rss
Feed Description: Posts about and around Ruby, MetaRuby, ruby2c, ZenTest and work at The Robot Co-op.
cdfh on #ruby-lang asked how to redirect $stdout per-thread and I came up with this solution, redirect via a thread-local variable:
##
# Allows $stdout to be set via Thread.current[:stdout] per thread.
module ThreadOut
##
# Writes to Thread.current[:stdout] instead of STDOUT if the thread local is
# set.
def self.write(stuff)
if Thread.current[:stdout] then
Thread.current[:stdout].write stuff
else
STDOUT.write stuff
end
end
end
$stdout = ThreadOut
Simple test:
require 'stringio'
require 'threadout'
s = StringIO.new
Thread.start do
Thread.current[:stdout] = s
puts 'redirected to StringIO'
end.join
Thread.start do
puts 'no redirection'
end.join
puts s.string