Class: Katte::ThreadPool

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(threads_num = 4, logger = Katte.app.logger) ⇒ ThreadPool

Returns a new instance of ThreadPool.



10
11
12
13
14
# File 'lib/katte/thread_pool.rb', line 10

def initialize(threads_num = 4, logger = Katte.app.logger)
  @queue         = Queue.new
  @threads_num   = threads_num
  @logger        = logger
end

Instance Attribute Details

#threadsObject (readonly)

Returns the value of attribute threads.



9
10
11
# File 'lib/katte/thread_pool.rb', line 9

def threads
  @threads
end

Class Method Details

.instanceObject



5
6
7
# File 'lib/katte/thread_pool.rb', line 5

def self.instance
  @instance ||= new.tap(&:run)
end

Instance Method Details

#joinObject



37
38
39
# File 'lib/katte/thread_pool.rb', line 37

def join
  @threads.each {|t| t.join}
end

#push(&procedure) ⇒ Object



29
30
31
# File 'lib/katte/thread_pool.rb', line 29

def push &procedure
  @queue.push procedure
end

#runObject



16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/katte/thread_pool.rb', line 16

def run
  procedure = Proc.new {
    loop {
      begin
        @queue.pop.call
      rescue => e
        @logger.error(e)
      end
    }
  }
  @threads ||= @threads_num.times.map { Thread.start &procedure }
end

#stopObject



33
34
35
# File 'lib/katte/thread_pool.rb', line 33

def stop
  @threads.each &:kill
end