<commit_before>class Parallelizer

  attr_accessor :thread_count

  def initialize(payloads)
    @queue = init_queue(payloads)
    @thread_count = default_thread_count
  end

  def run(&block)
    workers = (0..thread_count).map do
      Thread.new do
        process_payloads(&block)
      end
    end
    workers.each(&:join)
  end

  private

  def init_queue(payloads)
    Queue.new.tap do |q|
      payloads.each { |p| q.push(p) }
    end
  end

  def process_payloads
    ActiveRecord::Base.connection_pool.with_connection do
      while payload = next_payload # rubocop:disable Lint/AssignmentInCondition
        yield payload
      end
    end
  end

  def next_payload
    @queue.pop(true)
  rescue ThreadError # raised if called on an empty queue
    nil
  end

  def default_thread_count
    Rails.application.secrets.parallel_transcodings.to_i || 1
  end

end<commit_msg>fix parellelizer off-by-one issue<commit_after>class Parallelizer

  attr_accessor :thread_count

  def initialize(payloads)
    @queue = init_queue(payloads)
    @thread_count = default_thread_count
  end

  def run(&block)
    if thread_count <= 1
      process_payloads(&block)
    else
      run_parallel(&block)
    end
  end

  private

  def run_parallel(&block)
    workers = Array.new(thread_count) do
      Thread.new { process_payloads(&block) }
    end
    workers.each(&:join)
  end

  def init_queue(payloads)
    Queue.new.tap do |q|
      payloads.each { |p| q.push(p) }
    end
  end

  def process_payloads
    ActiveRecord::Base.connection_pool.with_connection do
      while payload = next_payload # rubocop:disable Lint/AssignmentInCondition
        yield payload
      end
    end
  end

  def next_payload
    @queue.pop(true)
  rescue ThreadError # raised if called on an empty queue
    nil
  end

  def default_thread_count
    Rails.application.secrets.parallel_transcodings.to_i
  end

end
{'fraction_non_alphanumeric': 0.07210526315789474, 'fraction_numerical': 0.0015789473684210526, 'mean_word_length': 2.9604166666666667, 'pattern_counts': {'":': 0, '<': 4, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7458864', 'n_tokens_mistral': 635, 'n_tokens_neox': 613, 'n_words': 145}