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

Returns a new instance of Pool.



203
204
205
206
207
208
209
210
211
212
213
214
# File 'lib/in_threads.rb', line 203

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.



201
202
203
# File 'lib/in_threads.rb', line 201

def exception
  @exception
end

Instance Method Details

#catchObject



234
235
236
237
238
239
# File 'lib/in_threads.rb', line 234

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

#finalizeObject



228
229
230
231
232
# File 'lib/in_threads.rb', line 228

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

#run(&block) ⇒ Object



216
217
218
# File 'lib/in_threads.rb', line 216

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

#stop!Object



224
225
226
# File 'lib/in_threads.rb', line 224

def stop!
  @stop = true
end

#stop?Boolean

Returns:

  • (Boolean)


220
221
222
# File 'lib/in_threads.rb', line 220

def stop?
  @stop || @exception
end