Ruby Language Merging Two Queues


  • 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 =
q2 =
(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 =

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

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 =
merged << q1.pop until q1.empty?
merged << q2.pop until q2.empty?