<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/css" href="/stylesheets/rss.css"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/">
  <channel>
    <title>Segment7: Setting $stdout per-thread</title>
    <link>http://blog.segment7.net/articles/2006/08/16/setting-stdout-per-thread</link>
    <language>en-us</language>
    <ttl>40</ttl>
    <description>The Blog</description>
    <item>
      <title>Setting $stdout per-thread</title>
      <description>cdfh on #ruby-lang asked how to redirect $stdout per-thread and I came up with this solution, redirect via a thread-local variable:

&lt;pre&gt;&lt;code&gt;##
# 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&lt;/code&gt;&lt;/pre&gt;

Simple test:

&lt;pre&gt;&lt;code&gt;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&lt;/code&gt;&lt;/pre&gt;

Output:

&lt;pre&gt;&lt;samp&gt;no redirection
redirected to StringIO&lt;/samp&gt;&lt;/pre&gt;
</description>
      <pubDate>Wed, 16 Aug 2006 11:58:00 -0700</pubDate>
      <guid isPermaLink="false">urn:uuid:67f648c0-e0f6-474b-9774-34b3da5861e4</guid>
      <author>drbrain@segment7.net (Eric Hodel)</author>
      <link>http://blog.segment7.net/articles/2006/08/16/setting-stdout-per-thread</link>
      <category>Hacking</category>
      <category>Ruby</category>
    </item>
  </channel>
</rss>
