ruby多线程

Ruby的Monitor库可以方便的实现这个功能,看下面的代码:

require 'monitor'
class Counter
   attr_reader :count
   def initialize
     @count = 0
     super
   end
   def tick
     @count += 1
   end
end
class Counter2 < Monitor
   attr_reader :count
   def initialize
     @count = 0
     super
   end
   def tick
     synchronize do
       @count += 1
     end
   end
end
c = Counter.new
t1 = Thread.new { 10000.times { c.tick } }
t2 = Thread.new { 10000.times { c.tick } }
t1.join
t2.join
puts c.count
c = Counter2.new
t1 = Thread.new { 10000.times { c.tick } }
t2 = Thread.new { 10000
t1.join
t2.join
puts c.count


你可能感兴趣的:(多线程,Ruby)