RubyスレッドセキュリティクラスMonitor

486 ワード

Monitorによるスレッドの同期は比較的安全です
require 'monitor'
class Counter
	attr_reader :count
	def initialize
		@count = 0
	end
	
	def tick
	  lock = Monitor.new
		lock.synchronize do
			@count += 1
		end
	end
end

c = Counter.new
t1 = Thread.new {100000.times {c.tick}}
t2 = Thread.new {100000.times {c.tick}}
t1.join
t2.join
puts c.count
#200000