Class: Threadded_enumerator::Yielder

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(args) ⇒ Yielder

Returns a new instance of Yielder.



129
130
131
132
133
134
135
# File 'lib/threadded_enumerator.rb', line 129

def initialize(args)
  @args = args
  @done = false
  @debug = @args[:debug]
  @results = Tsafe::MonArray.new
  @waiting_for_result = 0
end

Instance Attribute Details

#argsObject

Returns the value of attribute args.



127
128
129
# File 'lib/threadded_enumerator.rb', line 127

def args
  @args
end

#doneObject

Returns the value of attribute done.



127
128
129
# File 'lib/threadded_enumerator.rb', line 127

def done
  @done
end

#threadObject

Returns the value of attribute thread.



127
128
129
# File 'lib/threadded_enumerator.rb', line 127

def thread
  @thread
end

Instance Method Details

#<<(res) ⇒ Object

Adds a new result to the yielder.



138
139
140
141
142
143
144
145
146
# File 'lib/threadded_enumerator.rb', line 138

def <<(res)
  @results << res
  @waiting_for_result -= 1
  
  while @results.length >= @args[:cache] and @waiting_for_result <= 0
    print "Stopping thread - too many results (#{@results}).\n" if @debug
    Thread.stop
  end
end

#get_resultObject

Returns the next result.

Raises:

  • (StopIteration)


149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
# File 'lib/threadded_enumerator.rb', line 149

def get_result
  #Increase count to control cache.
  @waiting_for_result += 1
  
  #Wait for results-thread to be spawned before continuing.
  Thread.pass while !@thread
  
  #Raise error if thread results are done spawning (there wont be coming any more).
  raise StopIteration if @done and @results.empty?
  
  #Wait for new result and continue passing thread until results appear.
  while @results.empty?
    raise StopIteration if @done
    @thread.run if !@done and @thread.alive?
    Thread.pass
  end
  
  res = @results.shift
  @thread.run if !@done
  
  print "Returning: #{res}\n" if @debug
  return res
end