Method: Kennel::Utils.parallel

Defined in:
lib/kennel/utils.rb

.parallel(items, max: 10) ⇒ Object



108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
# File 'lib/kennel/utils.rb', line 108

def parallel(items, max: 10)
  threads = [items.size, max].min
  work = items.each_with_index.to_a
  done = Array.new(items.size)
  workers = Array.new(threads).map do
    Thread.new do
      loop do
        item, i = work.pop
        break unless i
        done[i] =
          begin
            yield item
          rescue Exception => e # rubocop:disable Lint/RescueException
            work.clear
            e
          end
      end
    end
  end
  workers.each(&:join)
  done.each { |d| raise d if d.is_a?(Exception) }
end