Class: ThreadPool
- Inherits:
-
Object
- Object
- ThreadPool
- Defined in:
- lib/thread_pool.rb
Defined Under Namespace
Classes: Worker
Instance Attribute Summary collapse
-
#max_size ⇒ Object
Returns the value of attribute max_size.
-
#workers ⇒ Object
readonly
Returns the value of attribute workers.
Instance Method Summary collapse
- #busy? ⇒ Boolean
- #create_worker ⇒ Object
- #find_available_worker ⇒ Object
- #free_worker ⇒ Object
-
#initialize(max_size = 10) ⇒ ThreadPool
constructor
A new instance of ThreadPool.
- #join ⇒ Object
- #process(&block) ⇒ Object
- #size ⇒ Object
- #wait_for_worker ⇒ Object
Constructor Details
#initialize(max_size = 10) ⇒ ThreadPool
Returns a new instance of ThreadPool.
43 44 45 46 47 |
# File 'lib/thread_pool.rb', line 43 def initialize(max_size = 10) @max_size = max_size @workers = [] @mutex = Mutex.new end |
Instance Attribute Details
#max_size ⇒ Object
Returns the value of attribute max_size.
40 41 42 |
# File 'lib/thread_pool.rb', line 40 def max_size @max_size end |
#workers ⇒ Object (readonly)
Returns the value of attribute workers.
41 42 43 |
# File 'lib/thread_pool.rb', line 41 def workers @workers end |
Instance Method Details
#busy? ⇒ Boolean
53 54 55 |
# File 'lib/thread_pool.rb', line 53 def busy? @mutex.synchronize {@workers.any? {|w| w.busy?}} end |
#create_worker ⇒ Object
81 82 83 84 85 86 |
# File 'lib/thread_pool.rb', line 81 def create_worker return nil if @workers.size >= @max_size worker = Worker.new @workers << worker worker end |
#find_available_worker ⇒ Object
73 74 75 |
# File 'lib/thread_pool.rb', line 73 def find_available_worker @mutex.synchronize {free_worker || create_worker} end |
#free_worker ⇒ Object
77 78 79 |
# File 'lib/thread_pool.rb', line 77 def free_worker @workers.each {|w| return w unless w.busy?}; nil end |
#join ⇒ Object
57 58 59 |
# File 'lib/thread_pool.rb', line 57 def join sleep 0.01 while busy? end |
#process(&block) ⇒ Object
61 62 63 |
# File 'lib/thread_pool.rb', line 61 def process(&block) wait_for_worker.set_block(block) end |
#size ⇒ Object
49 50 51 |
# File 'lib/thread_pool.rb', line 49 def size @mutex.synchronize {@workers.size} end |
#wait_for_worker ⇒ Object
65 66 67 68 69 70 71 |
# File 'lib/thread_pool.rb', line 65 def wait_for_worker while true worker = find_available_worker return worker if worker sleep 0.01 end end |