Class: Cosmo::Utils::ThreadPool
- Inherits:
-
Object
- Object
- Cosmo::Utils::ThreadPool
- Extended by:
- Forwardable
- Defined in:
- lib/cosmo/utils/thread_pool.rb
Overview
A thread pool that reuses a fixed number of threads operating off a fixed size queue. At any point, at most ‘num_threads` will be active processing tasks. When all threads are busy new tasks posted to the thread pool are blocked until a thread becomes available. Should a thread crash for any reason the thread will immediately be removed from the pool and replaced.
Instance Method Summary collapse
-
#initialize(concurrency) ⇒ ThreadPool
constructor
A new instance of ThreadPool.
- #post ⇒ Object
Constructor Details
#initialize(concurrency) ⇒ ThreadPool
Returns a new instance of ThreadPool.
17 18 19 20 21 22 |
# File 'lib/cosmo/utils/thread_pool.rb', line 17 def initialize(concurrency) @mutex = Thread::Mutex.new @available = concurrency @cond = ConditionVariable.new @pool = Concurrent::FixedThreadPool.new(concurrency) end |
Instance Method Details
#post ⇒ Object
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/cosmo/utils/thread_pool.rb', line 24 def post @mutex.synchronize do @cond.wait(@mutex) while @available <= 0 @available -= 1 end @pool.post do yield ensure @mutex.synchronize do @available += 1 @cond.signal end end end |