Ruby bounded thread worker pool
Ruby
def run_pool(items, workers: 4)
raise ArgumentError, 'workers must be positive' unless workers.positive?
jobs = Queue.new
results = Queue.new
items.each_with_index { |item, index| jobs << [item, index] }
workers.times { jobs << nil }
threads = workers.times.map do
Thread.new do
while (job = jobs.pop)
item, index = job
begin
results << [index, :ok, yield(item)]
rescue StandardError => error
results << [index, :error, error]
end
end
end
end
threads.each(&:join)
Array.new(items.size) { results.pop }.sort_by(&:first).map { |_, status, value| [status, value] }
end