class EasyThreadpool::Pool

Public Class Methods

new(size = 10) click to toggle source

Creating a new ThreadPool of size equal to @size It defines how many threads we will have spawned internally.

# File lib/easy_threadpool/pool.rb, line 8
def initialize(size = 10)
  # Pool size
  @size  = size
  # Queue holds tasks
  @queue = Queue.new
  # Threads are created
  @pool = Array.new(size) { |i| worker i}

  @consumed = 0
end

Public Instance Methods

process(*args, &block) click to toggle source

It schedules a job. The block of code will be executed once a thread is available

# File lib/easy_threadpool/pool.rb, line 21
def process(*args, &block)
  @queue << [block, args]
end
shutdown() click to toggle source

Graceful shutdown Always call pool.shutdow to ensure all of your enqueud task are executed

# File lib/easy_threadpool/pool.rb, line 28
def shutdown
  1.upto(@size) {|i| @queue << [:EXIT]}
  @pool.map(&:join)
end
shutdown!() click to toggle source

Force shutdown

# File lib/easy_threadpool/pool.rb, line 34
def shutdown!
  @pool.map(&:exit)
end
size() click to toggle source
# File lib/easy_threadpool/pool.rb, line 42
def size
  @size
end
task_consumed() click to toggle source
# File lib/easy_threadpool/pool.rb, line 38
def task_consumed
  @consumed
end

Private Instance Methods

worker(id) click to toggle source

It creates a task consumer :EXIT is a special internal message to handle Graceful shutdown

# File lib/easy_threadpool/pool.rb, line 49
def worker id
  Thread.new do
    Thread.current[:id] = id
    while true do
      code, args = @queue.pop
      break if code == :EXIT
      @consumed += 1
      code.call(*args)
    end
  end
end