Class: BBK::App::ThreadPool
- Inherits:
-
Object
- Object
- BBK::App::ThreadPool
- Defined in:
- lib/bbk/app/thread_pool.rb
Instance Attribute Summary collapse
-
#jobs ⇒ Object
readonly
Returns the value of attribute jobs.
-
#threads ⇒ Object
readonly
Returns the value of attribute threads.
Instance Method Summary collapse
-
#initialize(size, queue: 10) ⇒ ThreadPool
constructor
A new instance of ThreadPool.
- #kill(timeout = 1) ⇒ Object
- #post(*args, &block) ⇒ Object
- #shutdown ⇒ Object
- #wait_for_termination(timeout = 0) ⇒ Object (also: #wait)
Constructor Details
#initialize(size, queue: 10) ⇒ ThreadPool
Returns a new instance of ThreadPool.
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
# File 'lib/bbk/app/thread_pool.rb', line 9 def initialize(size, queue: 10) @jobs = SizedQueue.new(queue) @shutdown = false @term = false @threads = size.times.map do Thread.new(@jobs) do |jobs| begin Thread.current.report_on_exception = true Thread.current.abort_on_exception = true unless @shutdown until @term job, args = jobs.pop break if @term || job == :exit job.call(*args) end end rescue StandardError => e warn "[CRITICAL]: ThreadPool exception: #{e}" warn "[CRITICAL]: #{e.backtrace.join("\n")}" # Thread.main.raise e exit(1) end end end end |
Instance Attribute Details
#jobs ⇒ Object (readonly)
Returns the value of attribute jobs.
7 8 9 |
# File 'lib/bbk/app/thread_pool.rb', line 7 def jobs @jobs end |
#threads ⇒ Object (readonly)
Returns the value of attribute threads.
7 8 9 |
# File 'lib/bbk/app/thread_pool.rb', line 7 def threads @threads end |
Instance Method Details
#kill(timeout = 1) ⇒ Object
59 60 61 62 63 64 65 66 67 68 69 70 |
# File 'lib/bbk/app/thread_pool.rb', line 59 def kill(timeout = 1) return if @term @term = true shutdown if wait_for_termination(timeout) true else @threads.each(&:kill) false end end |
#post(*args, &block) ⇒ Object
38 39 40 |
# File 'lib/bbk/app/thread_pool.rb', line 38 def post(*args, &block) @jobs << [block, args] unless @shutdown end |
#shutdown ⇒ Object
42 43 44 45 46 47 |
# File 'lib/bbk/app/thread_pool.rb', line 42 def shutdown return if @shutdown @shutdown = true Thread.new { @threads.size.times { @jobs.push(:exit) } } end |
#wait_for_termination(timeout = 0) ⇒ Object Also known as: wait
49 50 51 52 53 54 55 |
# File 'lib/bbk/app/thread_pool.rb', line 49 def wait_for_termination(timeout = 0) Timeouter.run(timeout) do |t| @threads.all? do |thread| thread.join(t.left) end end end |