Module: Enumerable

Defined in:
lib/forkoff.rb

Instance Method Summary collapse

Instance Method Details

#forkoff(options = {}, &block) ⇒ Object Also known as: forkoff!



144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
# File 'lib/forkoff.rb', line 144

def forkoff options = {}, &block
#
  options = { 'processes' => Integer(options) } unless Hash === options
  n = Integer( options['processes'] || options[:processes] || Forkoff.default['processes'] )
  strategy = options['strategy'] || options[:strategy] || :pipe
  strategy_method = Forkoff::STRATEGIES[strategy]
  q = SizedQueue.new(n)
  result_sets = Array.new(n){ [] }

# consumers
#
  consumers =
    result_sets.map do |set|
      Thread.new do
        Thread.current.abort_on_exception = true

        loop do
          arg, index = q.pop
          break if index.nil?
          result = Forkoff.send( strategy_method, arg, &block )

          set.push [result, index]
        end

        set.push( :done )
      end
    end

# producers
#
  producer = 
    Thread.new do
      Thread.current.abort_on_exception = true
      each_with_index do |arg, i|
        q.push [arg, i]
      end
      n.times do |i|
        q.push( :done )
      end
    end

# wait for all consumers to complete
#
  consumers.each do |t|
    t.value
  end

# wait for the producer to complete
#
  producer.value

# gather results
#
  returned = []

  result_sets.each do |set|
    set.each do |result, index|
      break if index.nil?
      returned[index] = result
    end
  end

  returned
end