Class: Ninja::Threaded::ThreadPool

Inherits:
Object
  • Object
show all
Defined in:
lib/ninja/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) ⇒ ThreadPool

Default pool size is 2 threads.



88
89
90
91
92
93
# File 'lib/ninja/threaded.rb', line 88

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

Instance Attribute Details

#jobsObject (readonly)

The job queue.



68
69
70
# File 'lib/ninja/threaded.rb', line 68

def jobs
  @jobs
end

#sizeObject

The number of threads in the pool.



66
67
68
# File 'lib/ninja/threaded.rb', line 66

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.



97
98
99
100
101
102
103
104
# File 'lib/ninja/threaded.rb', line 97

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.



111
112
113
# File 'lib/ninja/threaded.rb', line 111

def njobs
  @njobs.to_i
end