Setting $stdout per-thread

Eric Hodel | Wed, 16 Aug 2006 18:58:00 GMT

Posted in ,

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
Output:
no redirection
redirected to StringIO
no comments

Comments RSS FEED

Comments are disabled