使用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
本文介绍了一种利用Monitor类确保线程安全的方法。通过一个简单的计数器示例,展示了如何在多线程环境下正确地增加计数器的值。此方案有效地避免了因并发操作导致的数据不一致问题。
390

被折叠的 条评论
为什么被折叠?



