Sha256: 00f8c76e5f1864812aed35e464ea7ecfb22547e424955e1c9c5c2b8d36ab9b35

Contents?: true

Size: 819 Bytes

Versions: 2

Compression:

Stored size: 819 Bytes

Contents

module Minions
  class Perform
    def initialize(work_packages, max:, &block)
      @work_packages = work_packages
      @max = [max, work_packages.length].min
      @work_block = block
    end

    def self.in_parallel(*args, &block)
      new(*args, &block).send(:in_parallel)
    end

    private

    attr_reader :work_packages, :max

    def in_parallel
      (0...max).map do
        Thread.new do
          begin
            while package = work_queue.pop(true)
              @work_block.call(package)
            end
          rescue ThreadError
            # The queue is empty
          end
        end
      end.map(&:join)
    end

    def work_queue
      @_work_queue ||= begin
        queue = Queue.new
        work_packages.each { |package| queue << package }
        queue
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
minions-0.1.2 lib/minions/perform.rb
minions-0.1.0 lib/minions/perform.rb