Class: Infrastruct::ThreadPool

Inherits:
Object
  • Object
show all
Defined in:
lib/infrastruct/thread_pool.rb

Instance Method Summary collapse

Constructor Details

#initialize(runner, threads:) ⇒ ThreadPool

Returns a new instance of ThreadPool.



3
4
5
6
7
8
# File 'lib/infrastruct/thread_pool.rb', line 3

def initialize(runner, threads:)
  @runner = runner
  @number_of_threads = threads
  @queue = Infrastruct::BlockingQueue.new
  @threads = []
end

Instance Method Details

#enqueue(args) ⇒ Object



10
11
12
# File 'lib/infrastruct/thread_pool.rb', line 10

def enqueue(args)
  @queue.push(args)
end

#finalizeObject



14
15
16
17
18
19
# File 'lib/infrastruct/thread_pool.rb', line 14

def finalize
  @queue.unblock!
  @threads.map(&:join)

  @runner.collect
end

#runObject



21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/infrastruct/thread_pool.rb', line 21

def run
  @threads = @number_of_threads.times.map do |n|
    Thread.new do
      begin
        while args = @queue.pop do
          @runner.perform(args)
        end
      rescue ThreadError => error
        raise error unless error.message == 'queue empty'
      end
    end
  end
end