One Source Multiple Workers
suggest changeWe 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)
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents