Class: PWork::ThreadPool

Inherits:
Object
  • Object
show all
Defined in:
lib/pwork/mri/thread_pool.rb,
lib/pwork/jruby/thread_pool.rb

Instance Method Summary collapse

Constructor Details

#initialize(threads: 5) ⇒ ThreadPool

Returns a new instance of ThreadPool.



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# File 'lib/pwork/mri/thread_pool.rb', line 3

def initialize(threads: 5)
  @size = threads
  @jobs = Queue.new
  @pool = Array.new(threads) do
    Thread.new do
      catch(:exit) do
        loop do
          job, thread_vars = @jobs.pop
          PWork::Helpers::Threads.set_thread_vars(thread_vars)
          job.call
        end
      end
    end
  end
end

Instance Method Details

#execute(&block) ⇒ Object

This method is called to pass a block to be ran on a thread within the thread pool



12
13
14
# File 'lib/pwork/jruby/thread_pool.rb', line 12

def execute(&block)
  @jobs << [block, PWork::Helpers::Threads.get_thread_vars]
end

#shutdownObject



23
24
25
26
27
28
29
# File 'lib/pwork/mri/thread_pool.rb', line 23

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

  @pool.map(&:join)
end