Class: SupplyDrop::ThreadPool

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

Instance Method Summary collapse

Constructor Details

#initialize(size) ⇒ ThreadPool

Returns a new instance of ThreadPool.



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/supply_drop/thread_pool.rb', line 5

def initialize(size)
  @size = size
  @jobs = Queue.new
  @retvals = []

  @pool = Array.new(@size) do |i|
    Thread.new do
      Thread.current[:id] = i

      catch(:exit) do
        loop do
          job, args = @jobs.pop
          @retvals << job.call(*args)
        end
      end
    end
  end
end

Instance Method Details

#schedule(*args, &block) ⇒ Object



25
26
27
# File 'lib/supply_drop/thread_pool.rb', line 25

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

#shutdownObject



30
31
32
33
34
35
36
37
# File 'lib/supply_drop/thread_pool.rb', line 30

def shutdown
  @size.times do
    schedule { throw :exit }
  end

  @pool.map(&:join)
  @retvals
end