Class: Af::ThreadPool
- Inherits:
-
Object
- Object
- Af::ThreadPool
- Defined in:
- lib/fiksu-af/thread_pool.rb
Defined Under Namespace
Classes: Worker
Instance Attribute Summary collapse
-
#max_size ⇒ Object
Returns the value of attribute max_size.
-
#thread_class ⇒ Object
Returns the value of attribute thread_class.
-
#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, thread_class = Thread) ⇒ ThreadPool
constructor
A new instance of ThreadPool.
- #join ⇒ Object
- #process(&block) ⇒ Object
- #size ⇒ Object
- #wait_for_worker ⇒ Object
Constructor Details
#initialize(max_size = 10, thread_class = Thread) ⇒ ThreadPool
Returns a new instance of ThreadPool.
48 49 50 51 52 53 |
# File 'lib/fiksu-af/thread_pool.rb', line 48 def initialize(max_size = 10, thread_class = Thread) @max_size = max_size @workers = [] @mutex = Mutex.new @thread_class = thread_class end |
Instance Attribute Details
#max_size ⇒ Object
Returns the value of attribute max_size.
45 46 47 |
# File 'lib/fiksu-af/thread_pool.rb', line 45 def max_size @max_size end |
#thread_class ⇒ Object
Returns the value of attribute thread_class.
45 46 47 |
# File 'lib/fiksu-af/thread_pool.rb', line 45 def thread_class @thread_class end |
#workers ⇒ Object (readonly)
Returns the value of attribute workers.
46 47 48 |
# File 'lib/fiksu-af/thread_pool.rb', line 46 def workers @workers end |
Instance Method Details
#busy? ⇒ Boolean
59 60 61 |
# File 'lib/fiksu-af/thread_pool.rb', line 59 def busy? @mutex.synchronize {@workers.any? {|w| w.busy?}} end |
#create_worker ⇒ Object
95 96 97 98 99 100 |
# File 'lib/fiksu-af/thread_pool.rb', line 95 def create_worker return nil if @workers.size >= @max_size worker = Worker.new(@thread_class) @workers << worker worker end |
#find_available_worker ⇒ Object
87 88 89 |
# File 'lib/fiksu-af/thread_pool.rb', line 87 def find_available_worker free_worker || create_worker end |
#free_worker ⇒ Object
91 92 93 |
# File 'lib/fiksu-af/thread_pool.rb', line 91 def free_worker @workers.each {|w| return w unless w.busy?}; nil end |
#join ⇒ Object
63 64 65 |
# File 'lib/fiksu-af/thread_pool.rb', line 63 def join sleep 0.01 while busy? end |
#process(&block) ⇒ Object
67 68 69 70 71 72 73 74 75 76 77 |
# File 'lib/fiksu-af/thread_pool.rb', line 67 def process(&block) while true @mutex.synchronize do worker = find_available_worker if worker return worker.set_block(block) end end sleep 0.01 end end |
#size ⇒ Object
55 56 57 |
# File 'lib/fiksu-af/thread_pool.rb', line 55 def size @mutex.synchronize {@workers.size} end |
#wait_for_worker ⇒ Object
79 80 81 82 83 84 85 |
# File 'lib/fiksu-af/thread_pool.rb', line 79 def wait_for_worker while true worker = find_available_worker return worker if worker sleep 0.01 end end |