Class: Parallel::JobFactory

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

Instance Method Summary collapse

Constructor Details

#initialize(source, mutex) ⇒ JobFactory

Returns a new instance of JobFactory.



99
100
101
102
103
104
105
# File 'lib/parallel.rb', line 99

def initialize(source, mutex)
  @lambda = (source.respond_to?(:call) && source) || queue_wrapper(source)
  @source = source.to_a unless @lambda # turn Range and other Enumerable-s into an Array
  @mutex = mutex
  @index = -1
  @stopped = false
end

Instance Method Details

#nextObject



107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
# File 'lib/parallel.rb', line 107

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 == Stop)
      return if @stopped
      [item, @index += 1]
    end
  else
    index = @mutex.synchronize { @index += 1 }
    return if index >= size
    item = @source[index]
  end
  [item, index]
end

#pack(item, index) ⇒ Object

generate item that is sent to workers just index is faster + less likely to blow up with unserializable errors



136
137
138
# File 'lib/parallel.rb', line 136

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

#sizeObject



126
127
128
129
130
131
132
# File 'lib/parallel.rb', line 126

def size
  if producer?
    Float::INFINITY
  else
    @source.size
  end
end

#unpack(data) ⇒ Object

unpack item that is sent to workers



141
142
143
# File 'lib/parallel.rb', line 141

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