class Tpool

Constants

ARGS_VALID

Attributes

args[R]

Public Class Methods

const_missing(name) click to toggle source
# File lib/tpool.rb, line 8
def self.const_missing(name)
  require "#{File.dirname(__FILE__)}/tpool_#{name.to_s.downcase}.rb"
  raise "Still not defined: '#{name}'." if !Tpool.const_defined?(name)
  return Tpool.const_get(name)
end
current_block(thread = Thread.current) click to toggle source

Returns the 'Tpool::Block' that is running in the given thread.

# File lib/tpool.rb, line 15
def self.current_block(thread = Thread.current)
  return thread[:tpool][:block] if thread[:tpool].is_a?(Hash)
  raise "No block was found running in that thread."
end
new(args) click to toggle source
# File lib/tpool.rb, line 20
def initialize(args)
  @args = args
  @args.each do |key, val|
    raise "Invalid argument given: '#{key}'." if Tpool::ARGS_VALID.index(key) == nil
  end
  
  @queue = Queue.new
  self.start
end

Public Instance Methods

on_error(&blk) click to toggle source
# File lib/tpool.rb, line 103
def on_error(&blk)
  @on_error = blk
end
on_error_call(*args) click to toggle source
# File lib/tpool.rb, line 99
def on_error_call(*args)
  @on_error.call(*args) if @on_error
end
run(*args, &blk) click to toggle source

Runs the given block in the thread-pool, joins it and returns the result.

# File lib/tpool.rb, line 63
def run(*args, &blk)
  raise "No block was given." if !blk
  
  block = Tpool::Block.new(
    :args => args,
    :blk => blk,
    :tpool => self,
    :thread_starts => [Thread.current]
  )
  @queue << block
  
  begin
    Thread.stop
  rescue Exception
    #Its not possible to stop main thread (dead-lock-error - sleep it instead).
    sleep 0.1 while !block.done?
  end
  
  return block.res
end
run_async(*args, &blk) click to toggle source

Runs the given block in the thread-pool and returns a block-object to keep a look on the status.

# File lib/tpool.rb, line 85
def run_async(*args, &blk)
  raise "No block was given." if !blk
  
  block = Tpool::Block.new(
    :tpool => self,
    :args => args,
    :blk => blk,
    :thread_starts => [Thread.current]
  )
  @queue << block
  
  return block
end
start() click to toggle source

Starts the thread-pool. This is automatically called on initialization.

# File lib/tpool.rb, line 31
def start
  raise "Already started." if @pool and !@pool.empty?
  
  @pool = Array.new(@args[:threads]) do |i|
    Thread.new do
      begin
        Thread.current[:tpool] = {:i => i}
        
        loop do
          block = @queue.pop
          Thread.current[:tpool][:block] = block
          
          block.run
          Thread.current[:tpool].delete(:block)
        end
      rescue Exception => e
        $stderr.puts e.inspect
        $stderr.puts e.backtrace
      end
    end
  end
end
stop() click to toggle source

Kills all running threads.

# File lib/tpool.rb, line 55
def stop
  @pool.delete_if do |thread|
    thread.kill
    true
  end
end