Class: Parallel::ItemWrapper

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

Instance Method Summary collapse

Constructor Details

#initialize(array, mutex) ⇒ ItemWrapper

Returns a new instance of ItemWrapper.



67
68
69
70
71
72
73
# 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

Instance Method Details

#each_with_index(&block) ⇒ Object



79
80
81
82
83
84
85
86
87
88
89
# 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

#nextObject



91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# 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) ⇒ Object



114
115
116
# File 'lib/parallel.rb', line 114

def pack(item, index)
  producer? ? [item, index] : index
end

#producer?Boolean

Returns:

  • (Boolean)


75
76
77
# File 'lib/parallel.rb', line 75

def producer?
  @lambda
end

#queue_wrapper(array) ⇒ Object



122
123
124
# File 'lib/parallel.rb', line 122

def queue_wrapper(array)
  array.respond_to?(:num_waiting) && array.respond_to?(:pop) && lambda { array.pop(false) }
end

#sizeObject



110
111
112
# File 'lib/parallel.rb', line 110

def size
  @items.size
end

#unpack(data) ⇒ Object



118
119
120
# File 'lib/parallel.rb', line 118

def unpack(data)
  producer? ? data : [@items[data], data]
end