Use SizedQueue to coordinate producer and consumer
require "thread"
buffer = SizedQueue.new(2)
producer = Thread.new do
item = 0
loop do
sleep rand 0
puts "Producer makes #{item}"
buffer.enq item
item += 1
end
end
consumer = Thread.new do
loop do
sleep (rand 0)+0.9
item = buffer.deq
puts "Consumer retrieves #{item}"
puts " waiting = #{buffer.num_waiting}"
end
end
Related examples in the same category