One Source Multiple Workers

suggest change

We want to process data in parallel.

Let’s populate source with some data:

source = Queue.new
data = (1..100)
data.each { |e| source << e }

Then create some workers to process data. pop with no argument waits forever when the queue is empty, and empty? followed by pop races with the other workers. pop(true) raises ThreadError instead of waiting:

(1..16).to_a.map do
  Thread.new do
    loop do
      begin
        item = source.pop(true)
      rescue ThreadError
        break
      end
      sleep 0.5
      puts "Processed: #{item}"
    end
  end
end.map(&:join)

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents