Class: Bob::Engine::Threaded::ThreadPool

Inherits:
Object
  • Object
show all
Defined in:
lib/bob/engine/threaded.rb

Overview

Manage a pool of threads, allowing for spin up / spin down of the contained threads. Simply processes work added to it’s queue via #push. The default size for the pool is 2 threads.

Defined Under Namespace

Classes: Incrementor

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(size = nil, logger = Bob.logger) ⇒ ThreadPool

Default pool size is 2 threads.



94
95
96
97
98
99
100
# File 'lib/bob/engine/threaded.rb', line 94

def initialize(size = nil, logger = Bob.logger)
  size ||= 2
  @jobs    = Queue.new
  @njobs   = Incrementor.new
  @workers = Array.new(size) { spawn }
  @logger  = logger
end

Instance Attribute Details

#jobsObject (readonly)

The job queue.



74
75
76
# File 'lib/bob/engine/threaded.rb', line 74

def jobs
  @jobs
end

#sizeObject

The number of threads in the pool.



71
72
73
# File 'lib/bob/engine/threaded.rb', line 71

def size
  @size
end

Instance Method Details

#add(*jobs, &blk) ⇒ Object Also known as: push, <<

Adds a job to the queue, the job can be any number of objects responding to call, and/or a block.



104
105
106
107
108
109
110
111
# File 'lib/bob/engine/threaded.rb', line 104

def add(*jobs, &blk)
  jobs = jobs + Array(blk)

  jobs.each do |job|
    @jobs << job
    @njobs.inc
  end
end

#njobsObject

A peak at the number of jobs in the queue. N.B. May differ, but should be more accurate than jobs.size.



118
119
120
# File 'lib/bob/engine/threaded.rb', line 118

def njobs
  @njobs.to_i
end