Concurrency Basics
Queue Handoff
A queue lets one thread hand values to another thread safely.
Queue Handoff
queue_handoff.rb
item_count =
queue = Queue.new
received = []
producer = Thread.new do
item_count.times do |index|
queue.push("item#{index + 1}")
end
queue.push(:done)
end
consumer = Thread.new do
loop do
item = queue.pop
break if item == :done
received << item
end
end
producer.join
consumer.join
puts "item_count=#{item_count}"
puts "received=#{received.join("/")}"
puts "complete=#{received.length == item_count}"
item_count =
queue = Queue.new
received = []
producer = Thread.new do
item_count.times do |index|
queue.push("item#{index + 1}")
end
queue.push(:done)
end
consumer = Thread.new do
loop do
item = queue.pop
break if item == :done
received << item
end
end
producer.join
consumer.join
puts "item_count=#{item_count}"
puts "received=#{received.join("/")}"
puts "complete=#{received.length == item_count}"
item_count =
queue = Queue.new
received = []
producer = Thread.new do
item_count.times do |index|
queue.push("item#{index + 1}")
end
queue.push(:done)
end
consumer = Thread.new do
loop do
item = queue.pop
break if item == :done
received << item
end
end
producer.join
consumer.join
puts "item_count=#{item_count}"
puts "received=#{received.join("/")}"
puts "complete=#{received.length == item_count}"
queue handoff
`Queue#push` and `Queue#pop` coordinate producer and consumer code without manual locking.