The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
Setting $stdout per-thread

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Eric Hodel

Posts: 660
Nickname: drbrain
Registered: Mar, 2006

Eric Hodel is a long-time Rubyist and co-founder of Seattle.rb.
Setting $stdout per-thread Posted: Aug 16, 2006 1:48 PM
Reply to this message Reply

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.
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by Eric Hodel
Latest Posts From Segment7

Advertisement
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

Read: Setting $stdout per-thread

Topic: A Useful Sign Previous Topic   Next Topic Topic: Photo Update

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use