Class: Integer

Inherits:
Object
  • Object
show all
Defined in:
lib/dispatch/enumerable.rb

Instance Method Summary collapse

Instance Method Details

#p_times(stride = 1, priority = nil, &block) ⇒ Object

Applies the &block Integer number of times in parallel – passing in stride (default 1) iterations at a time – on a concurrent queue of the given (optional) priority

@sum = 0
10.p_times(3) { |j| @sum += j }
p @sum # => 55


25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/dispatch/enumerable.rb', line 25

def p_times(stride=1, priority=nil, &block)
  n_times = self.to_int
  q = Dispatch::Queue.concurrent(priority)
  return q.apply(n_times, &block) if stride == 1
  
  n_strides = (n_times / stride).to_int
  block_from = Proc.new do |j0|
    lambda { |j| block.call(j0+j) }
  end
  q.fake_apply(n_strides) { |i| stride.times &block_from.call(i*stride) }
  # Runs the remainder (if any) sequentially on the current thread
  (n_times % stride).times &block_from.call(n_strides*stride)
end