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多线程

相关文章:

你感兴趣的文章:

标签云: