使用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