class Universa::Parallel::ParallelEnumerable

The eollection-like delegate supporting parallel execution on {#each}, {#each_with_index} and {#map}. Use +refine Enumerable+ to easily construct it as simple as collection.par. Inspired by Scala.

Public Instance Methods

collect(&block)
Alias for: map
each(&block) click to toggle source

Call the given block on each item in the collection in parallel, blocks until all items are processed

@return self

# File lib/universa/tools.rb, line 56
def each &block
  each_with_index {|x, i| block.call(x)}
end
each_with_index(&block) click to toggle source

Enumerates in parallel all items. Like +Enumerable#each_with_index+, but requires block. Blocks until all items are processed.

@param [Proc] block to call with (object, index) parameters @return self

# File lib/universa/tools.rb, line 36
def each_with_index &block
  latch = CountDownLatch.new(size)
  __getobj__.each_with_index {|x, index|
    @@pool << -> {
      begin
        block.call(x, index)
      rescue
        $!.print_stack_trace
      ensure
        latch.count_down
      end
    }
  }
  latch.wait
  self
end
map(&block) click to toggle source

Parallel version of the +Enumerable#map+. Creates a new array containing the values returned by the block, using parallel execution in threads.

@return new array containing the values returned by the block.

# File lib/universa/tools.rb, line 64
def map &block
  result = size.times.map {nil}
  each_with_index {|value, i|
    result[i] = block.call(value)
  }
  result.par
end
Also aliased as: collect