Class: Pool

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

Overview

Class that creates a thread safe pool.

Instance Method Summary collapse

Constructor Details

#initialize(size) ⇒ Pool

Returns a new instance of Pool.



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/npsearch/pool.rb', line 28

def initialize(size)
  @size = size
  @jobs = Queue.new
  @pool = Array.new(@size) do |i|
    Thread.new do
      Thread.current[:id] = i
      catch(:exit) do
        loop do
          job, args = @jobs.pop
          job.call(*args)
        end
      end
    end
  end
end

Instance Method Details

#schedule(*args, &block) ⇒ Object



44
45
46
# File 'lib/npsearch/pool.rb', line 44

def schedule(*args, &block)
  @jobs << [block, args]
end

#shutdownObject



48
49
50
51
52
53
# File 'lib/npsearch/pool.rb', line 48

def shutdown
  @size.times do
    schedule { throw :exit }
  end
  @pool.map(&:join)
end