Class: ThreadPool

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

Defined Under Namespace

Modules: Completable Classes: Executor

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(count, queue_limit = 0) ⇒ ThreadPool

Initialize with number of threads to run



44
45
46
47
48
49
50
51
# File 'lib/thread_pool.rb', line 44

def initialize(count, queue_limit = 0)
  @mutex = Mutex.new
  @executors = []
  @queue = []
  @queue_limit = queue_limit
  @count = count    
  count.times { @executors << Executor.new(@queue, @mutex) }
end

Instance Attribute Details

#queue_limitObject

Returns the value of attribute queue_limit.



41
42
43
# File 'lib/thread_pool.rb', line 41

def queue_limit
  @queue_limit
end

Instance Method Details

#closeObject

Kills all threads



83
84
85
# File 'lib/thread_pool.rb', line 83

def close
  @executors.each {|e| e.close }
end

#execute(*args, &block) ⇒ Object

Runs the block at some time in the near future



54
55
56
57
58
59
60
61
62
63
64
# File 'lib/thread_pool.rb', line 54

def execute(*args, &block)
  init_completable(block)
  
  if @queue_limit > 0
    sleep 0.01 until @queue.size < @queue_limit
  end
    
  @mutex.synchronize do
    @queue << [args, block]
  end
end

#joinObject

Sleeps and blocks until the task queue is finished executing



88
89
90
# File 'lib/thread_pool.rb', line 88

def join
  sleep 0.01 until @queue.empty? && @executors.all?{|e| !e.active}
end

#sizeObject

Size of the thread pool



78
79
80
# File 'lib/thread_pool.rb', line 78

def size
  @count
end

#synchronous_execute(*args, &block) ⇒ Object

Runs the block at some time in the near future, and blocks until complete



67
68
69
70
# File 'lib/thread_pool.rb', line 67

def synchronous_execute(*args, &block)
  execute(*args, &block)
  sleep 0.01 until block.complete?
end

#waitingObject

Size of the task queue



73
74
75
# File 'lib/thread_pool.rb', line 73

def waiting
  @queue.size
end