Class: Threadpool
- Inherits:
-
Object
- Object
- Threadpool
- Defined in:
- lib/batsd/threadpool.rb
Overview
A basic implementation of a FIFO worker threadpool
Instance Method Summary (collapse)
-
- (Threadpool) initialize(size)
constructor
Create a new threadpool, complete with queue and a spun up pool of size workers.
-
- (Object) pool
Returns the size of the pool of workers.
-
- (Object) queue(*args, &block)
Add a new procedure to the queue.
-
- (Object) size
Returns the size of the queue of outstanding jobs.
Constructor Details
- (Threadpool) initialize(size)
Create a new threadpool, complete with queue and a spun up pool of size workers. Workers will be active immediately
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
# File 'lib/batsd/threadpool.rb', line 9 def initialize(size) @queue = Queue.new @pool = [] size.times do |i| @pool << Thread.new do loop do job, args = @queue.pop begin job.call(*args) rescue Exception => e puts "Thread #{Thread.current} error: #{e} #{e.message} #{e.backtrace.join("\n")}" end end end end end |
Instance Method Details
- (Object) pool
Returns the size of the pool of workers
47 48 49 |
# File 'lib/batsd/threadpool.rb', line 47 def pool @pool.size end |
- (Object) queue(*args, &block)
Add a new procedure to the queue
Example:
@threadpool.queue arg1, arg2 do |x, y|
puts x # will be equal to arg1
puts y # will be equal to arg2
end
35 36 37 |
# File 'lib/batsd/threadpool.rb', line 35 def queue(*args, &block) @queue << [block, args] end |
- (Object) size
Returns the size of the queue of outstanding jobs
41 42 43 |
# File 'lib/batsd/threadpool.rb', line 41 def size @queue.size end |