1# encoding: utf-8
2######################################################################
3# This file is imported from the minitest project.
4# DO NOT make modifications in this repo. They _will_ be reverted!
5# File a patch instead and assign it to Ryan Davis.
6######################################################################
7
8class ParallelEach
9  require 'thread'
10  include Enumerable
11
12  N = (ENV['N'] || 2).to_i
13
14  def initialize list
15    @queue = Queue.new # *sigh*... the Queue api sucks sooo much...
16
17    list.each { |i| @queue << i }
18    N.times { @queue << nil }
19  end
20
21  def grep pattern
22    self.class.new super
23  end
24
25  def each
26    threads = N.times.map {
27      Thread.new do
28        Thread.current.abort_on_exception = true
29        while job = @queue.pop
30          yield job
31        end
32      end
33    }
34    threads.map(&:join)
35  end
36end
37