Class: HQ::Tools::ThreadPool
- Inherits:
-
Object
- Object
- HQ::Tools::ThreadPool
- Defined in:
- lib/hq/tools/thread-pool.rb
Instance Method Summary collapse
- #deinit_hook(&block) ⇒ Object
- #init_hook(&block) ⇒ Object
-
#initialize ⇒ ThreadPool
constructor
A new instance of ThreadPool.
- #schedule(*args, &block) ⇒ Object
- #start(threads) ⇒ Object
- #stop ⇒ Object
- #worker_deinit ⇒ Object
- #worker_init ⇒ Object
- #worker_run ⇒ Object
Constructor Details
#initialize ⇒ ThreadPool
Returns a new instance of ThreadPool.
6 7 8 9 |
# File 'lib/hq/tools/thread-pool.rb', line 6 def initialize require "thread" @tasks = Queue.new end |
Instance Method Details
#deinit_hook(&block) ⇒ Object
42 43 44 |
# File 'lib/hq/tools/thread-pool.rb', line 42 def deinit_hook &block @deinit_hook = block end |
#init_hook(&block) ⇒ Object
38 39 40 |
# File 'lib/hq/tools/thread-pool.rb', line 38 def init_hook &block @init_hook = block end |
#schedule(*args, &block) ⇒ Object
34 35 36 |
# File 'lib/hq/tools/thread-pool.rb', line 34 def schedule *args, &block @tasks << [ block, args ] end |
#start(threads) ⇒ Object
46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
# File 'lib/hq/tools/thread-pool.rb', line 46 def start threads @threads = Array.new threads do Thread.new do worker_init worker_run worker_deinit end end end |
#stop ⇒ Object
61 62 63 64 65 66 67 68 69 70 71 72 |
# File 'lib/hq/tools/thread-pool.rb', line 61 def stop @threads.size.times do schedule { throw :exit } end @threads.each do |thread| thread.join end end |
#worker_deinit ⇒ Object
29 30 31 32 |
# File 'lib/hq/tools/thread-pool.rb', line 29 def worker_deinit return unless @deinit_hook @deinit_hook.call end |
#worker_init ⇒ Object
11 12 13 14 |
# File 'lib/hq/tools/thread-pool.rb', line 11 def worker_init return unless @init_hook @init_hook.call end |
#worker_run ⇒ Object
16 17 18 19 20 21 22 23 24 25 26 27 |
# File 'lib/hq/tools/thread-pool.rb', line 16 def worker_run catch :exit do loop do task, args = @tasks.pop task.call *args end end end |