module Shotgunner::Parallel::ClassMethods

Public Instance Methods

run(options = {}) { |task| ... } click to toggle source
# File lib/shotgunner/parallel.rb, line 17
def run(options = {}, &block)
  call_results, mutex, tasks, threads = initiate(options)
  
  validate_params(tasks, threads)
  
  threads.times.map do
    Thread.new(tasks, call_results) do |tasks, call_results|
      while (task = mutex.synchronize { tasks.pop })
        call_result = yield(task)
        mutex.synchronize { call_results[task] = call_result }
      end
    end
  end.each(&:join)
  
  call_results.map{|v| v[1]}
end

Private Instance Methods

initiate(options) click to toggle source
# File lib/shotgunner/parallel.rb, line 41
def initiate(options)
  mutex = Mutex.new
  threads = options[:threads] || 4
  tasks = options[:tasks]&.dup || []
  call_results = Hash[tasks.map { |x| [x, nil] }]
  [call_results, mutex, tasks, threads]
end
validate_params(tasks, threads) click to toggle source
# File lib/shotgunner/parallel.rb, line 36
def validate_params(tasks, threads)
  raise ArgumentError, 'There is no tasks array defined!' if tasks.empty?
  raise ArgumentError, 'Invalid threads number, please select number from 1..100' unless threads&.between?(1, 100)
end