class Parallel::JobFactory
def initialize(source, mutex)
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
def next
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
def pack(item, index)
generate item that is sent to workers
def pack(item, index) producer? ? [item, index] : index end
def producer?
def producer? @lambda end
def queue_wrapper(array)
def queue_wrapper(array) array.respond_to?(:num_waiting) && array.respond_to?(:pop) && -> { array.pop(false) } end
def size
def size if producer? Float::INFINITY else @source.size end end
def unpack(data)
def unpack(data) producer? ? data : [@source[data], data] end