今日のRuby
Monitorの練習
require 'thread' require 'monitor' $found = [] $monitor = Monitor.new def have_found?(i) $monitor.synchronize do return $found.include?(i) end end tg = [] 3.times{ tg << Thread.new{ while $found.length < 100 i = rand(100) if have_found?(i) puts "#{i} has been found" else $monitor.synchronize do puts "#{Thread.current} adds #{i} to $found" $found << i p $found end end Thread.pass end } } tg.each{|th| th.join }
メソッド名を"have_found?"にするか、"has_found"にするかで悩んだが、
まあhaveで。