Class: Parallel::ItemWrapper
- Inherits:
-
Object
- Object
- Parallel::ItemWrapper
- Defined in:
- lib/parallel.rb
Instance Method Summary collapse
- #each_with_index(&block) ⇒ Object
-
#initialize(array, mutex) ⇒ ItemWrapper
constructor
A new instance of ItemWrapper.
- #next ⇒ Object
- #pack(item, index) ⇒ Object
- #producer? ⇒ Boolean
- #queue_wrapper(array) ⇒ Object
- #size ⇒ Object
- #unpack(data) ⇒ Object
Constructor Details
#initialize(array, mutex) ⇒ ItemWrapper
Returns a new instance of ItemWrapper.
67 68 69 70 71 72 |
# 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 end |
Instance Method Details
#each_with_index(&block) ⇒ Object
78 79 80 81 82 83 84 85 86 87 88 |
# File 'lib/parallel.rb', line 78 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 ⇒ Object
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 |
# File 'lib/parallel.rb', line 90 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
113 114 115 |
# File 'lib/parallel.rb', line 113 def pack(item, index) producer? ? [item, index] : index end |
#producer? ⇒ Boolean
74 75 76 |
# File 'lib/parallel.rb', line 74 def producer? @lambda end |
#queue_wrapper(array) ⇒ Object
121 122 123 |
# File 'lib/parallel.rb', line 121 def queue_wrapper(array) array.respond_to?(:num_waiting) && array.respond_to?(:pop) && lambda { array.pop(false) } end |
#size ⇒ Object
109 110 111 |
# File 'lib/parallel.rb', line 109 def size @items.size end |
#unpack(data) ⇒ Object
117 118 119 |
# File 'lib/parallel.rb', line 117 def unpack(data) producer? ? data : [@items[data], data] end |