From: Takashi SUGA Date: 2010-11-30T20:22:07+09:00 Subject: [ruby-list:47663] スレッドの中でのハッシュの更新 みなさん、お久しぶりです。 首記の件、下に記したサンプルの様な処理の際、(*2)の書き込み中に、 中途半端な状態で(*1)の読み出しが行われるようなことはないのでしょうか? Version 1.8 以前は Ruby が自前でスレッドを管理していたので、アトミック であることが保証されていたはずですが、OSネイティブのスレッド機能を用いる 1.9 でも大丈夫なのでしょうか? ------------------------------------------------------------------ require 'thread' class Test def initialize # @mutex = Mutex.new @cash = {} end def fib(n, locked=false) locked ||= !@mutex return (n<=1) ? n : fib(n-1) + fib(n-2) unless locked || @mutex.try_lock begin return @cash[n] if @cash[n] # (*1) # p [n, locked, Thread.current.to_s] @cash[n] = (n<=1) ? n : fib(n-1, true) + fib(n-2, true) # (*2) is critical ? return @cash[n] ensure @mutex.unlock unless locked end end end a = Test.new 2.times {|i| Thread.new(i) {|n| 10.times {|k| a.fib(2*k+n)}}.join} ------------------------------------------------------------------ ******* 須賀 隆 **** http://www.asahi-net.or.jp/~dd6t-sg/ *******