ruby多线程
- 摘要:Ruby的Monitor库可以方便的实现这个功能,看下面的代码:require'monitor'classCounterattr_reader:countdefinitialize@count=0superenddeftick@count+=1endendclassCounter2<Monitorattr_reader:countdefinitialize@count=0superenddefticksynchronizedo@count+=1endendendc=Counter
- 标签:多线程 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