Ruby语言中直接提供了Monitor的支持,因此可以如下实现Producer-Consumer:
require 'monitor'
N = 10
BUFFER = Array.new(N)
class ProducerConsumer < Monitor
def initialize
@count = 0
super
end
def insert(item)
if @count == N
puts "buffer is full"
Thread.pass
end
insert_item(item)
puts "item inserted"
@count += 1
end
def remove
if @count == 0
puts "buffer is empty"
Thread.pass
end
remove_item
puts "item removed"
@count -= 1
end
private
def insert_item(item)
BUFFER << item
end
def remove_item
item = BUFFER.delete_at(@count - 1)
end
end
m = ProducerConsumer.new
producer = Thread.start {
while true
m.insert(1)
end
}
consumer = Thread.start {
while true
item = m.remove
end
}
producer.join
consumer.join
也可以利用Ruby的mixin特性,不继承Monitor:
require 'monitor'
class ProducerConsumer
include MonitorMixin
//以下代码同上
...