thread_pool

Emad Elsaid · @emad-elsaid · about 4 years

This function takes an array of objects and executes a method in each object in parallel in multiple threads

def thread_pool(objects:, method:, pool_size:)
queue = Queue.new
objects.each { |obj| queue << obj }
(0...pool_size).map do
Thread.new do
while object = queue.pop(true)
begin
puts "Executing: #{object}#.#{method}"
object.send(method)
rescue StandardError => e
puts "Error processing #{object} #{e}"
end
end
rescue ThreadError
true
end
end.map(&:join)
end
4 · 0 · 3