class Parallel::ItemWrapper

Public Class Methods

new(array, mutex) click to toggle source
# File lib/parallel.rb, line 67
def initialize(array, mutex)
  @lambda = (array.respond_to?(:call) && array) || queue_wrapper(array)
  @items = array.to_a unless @lambda # turn Range and other Enumerable-s into an Array
  @mutex = mutex
  @index = -1
  @stopped = false
end

Public Instance Methods

each_with_index() { |item, index| ... } click to toggle source
# File lib/parallel.rb, line 79
def each_with_index(&block)
  if producer?
    loop do
      item, index = self.next
      break unless index
      yield(item, index)
    end
  else
    @items.each_with_index(&block)
  end
end
next() click to toggle source
# File lib/parallel.rb, line 91
def next
  if producer?
    # - index and item stay in sync
    # - do not call lambda after it has returned Stop
    item, index = @mutex.synchronize do
      return if @stopped
      item = @lambda.call
      @stopped = (item == Parallel::Stop)
      return if @stopped
      [item, @index += 1]
    end
  else
    index = @mutex.synchronize { @index += 1 }
    return if index >= size
    item = @items[index]
  end
  [item, index]
end
pack(item, index) click to toggle source
# File lib/parallel.rb, line 114
def pack(item, index)
  producer? ? [item, index] : index
end
producer?() click to toggle source
# File lib/parallel.rb, line 75
def producer?
  @lambda
end
queue_wrapper(array) click to toggle source
# File lib/parallel.rb, line 122
def queue_wrapper(array)
  array.respond_to?(:num_waiting) && array.respond_to?(:pop) && lambda { array.pop(false) }
end
size() click to toggle source
# File lib/parallel.rb, line 110
def size
  @items.size
end
unpack(data) click to toggle source
# File lib/parallel.rb, line 118
def unpack(data)
  producer? ? data : [@items[data], data]
end