Class: InThreads::Pool

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

Overview

Thread pool

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(thread_count) ⇒ Pool



172
173
174
175
176
177
178
179
180
181
182
183
# File 'lib/in_threads.rb', line 172

def initialize(thread_count)
  @queue = Queue.new
  @mutex = Mutex.new
  @pool = Array.new(thread_count) do
    Thread.new do
      while (block = @queue.pop)
        block.call
        break if stop?
      end
    end
  end
end

Instance Attribute Details

#exceptionObject (readonly)

Returns the value of attribute exception.



170
171
172
# File 'lib/in_threads.rb', line 170

def exception
  @exception
end

Instance Method Details

#catchObject



203
204
205
206
207
208
# File 'lib/in_threads.rb', line 203

def catch
  yield
rescue Exception => e
  @mutex.synchronize{ @exception ||= e } unless @exception
  nil
end

#finalizeObject



197
198
199
200
201
# File 'lib/in_threads.rb', line 197

def finalize
  @pool.
    each{ @queue.push(nil) }.
    each(&:join)
end

#run(&block) ⇒ Object



185
186
187
# File 'lib/in_threads.rb', line 185

def run(&block)
  @queue.push(block)
end

#stop!Object



193
194
195
# File 'lib/in_threads.rb', line 193

def stop!
  @stop = true
end

#stop?Boolean



189
190
191
# File 'lib/in_threads.rb', line 189

def stop?
  @stop || @exception
end