Ruby Language Queue Merging Two Queues


Example

  • To avoid infinitely blocking, reading from queues shouldn't happen on the thread merge is happening on.
  • To avoid synchronization or infinitely waiting for one of queues while other has data, reading from queues shouldn't happen on same thread.

Let's start by defining and populating two queues:

q1 = Queue.new
q2 = Queue.new
(1..100).each { |e| q1 << e }
(101..200).each { |e| q2 << e }

We should create another queue and push data from other threads into it:

merged = Queue.new

[q1, q2].map do |q|
  Thread.new do
    loop do
      merged << q.pop
    end
  end
end

If you know you can completely consume both queues (consumption speed is higher than production, you won't run out of RAM) there is a simpler approach:

merged = Queue.new
merged << q1.pop until q1.empty?
merged << q2.pop until q2.empty?