それマグで!

知識はカップより、マグでゆっくり頂きます。 takuya_1stのブログ

習慣に早くから配慮した者は、 おそらく人生の実りも大きい。

Rubyでマルチスレッド 13 #thread specific Storage

Ruby結城浩せんせいのJavaマルチスレッド本 その13 # thread specific storage

スレッド毎の領域

スレッド毎に排他的なストレージ領域。スレッドはそれを使ってるのを知らない。

rubyで実装

Logを書くだけのモノ

#!/usr/bin/env ruby
# ThreadSpecific Storage
class TSLog
  def initialize fname
    @file = open fname, "w"
  end
  def println s
    @file.puts s
  end
  def close
    @file.puts "==== END OF LOG ===="
    @file.close
  end
end
class Log
  def Log.println s
    logger = get_ts_log().println(s)
  end
  def Log.get_ts_log
    logger =  Thread.current[:logger]
    if logger == nil then
      Thread.current[:logger] = TSLog.new( Thread.current[:name]+"-log.txt")
      logger =  Thread.current[:logger]
    end
    logger
  end
  def Log.close
    Log.get_ts_log().close
  end
end
class ClientThread
  def initialize name
    @name = name
  end
  def start
    t=Thread.new(@name){|name|
      Thread.current[:name] = name
      puts "#{@name} BEGIN "
      10.times{|i|
        Log.println( "i = #{i}" )
        sleep rand(999).to_f/1000
      }
      Log.close
      puts "#{@name} END "
    }
    t
  end
end
threads= [
    ClientThread.new("Alice").start(),
    ClientThread.new("Bobby").start(),
    ClientThread.new("Chris").start(),
  ].each{|t|t.join}
puts "END"

実行結果

Alice-log.txt, Bobby-log.txt, Chris-log.txt
i = 0
i = 1
i = 2

スレッドが変わっても同じ

        Log.println( "i = #{i}" )

スレッドを全部まとめて扱える