Class: Breeder::BreedingStrategy::Threads
- Inherits:
-
Object
- Object
- Breeder::BreedingStrategy::Threads
- Defined in:
- lib/breeder/breeding_strategy/threads.rb
Instance Method Summary collapse
- #create_worker ⇒ Object
-
#initialize(worker_factory, initial_workers) ⇒ Threads
constructor
A new instance of Threads.
- #num_workers ⇒ Object
- #reap! ⇒ Object
- #spawn! ⇒ Object
- #start! ⇒ Object
- #stop! ⇒ Object
Constructor Details
#initialize(worker_factory, initial_workers) ⇒ Threads
Returns a new instance of Threads.
5 6 7 8 9 10 |
# File 'lib/breeder/breeding_strategy/threads.rb', line 5 def initialize(worker_factory, initial_workers) @threads = [] @workers = [] @worker_factory = worker_factory @initial_workers = initial_workers end |
Instance Method Details
#create_worker ⇒ Object
24 25 26 27 28 29 30 31 |
# File 'lib/breeder/breeding_strategy/threads.rb', line 24 def create_worker raise "No worker factory specified" unless !!@worker_factory worker = @worker_factory.call unless [:run, :stop!, :stop?].all? { |method| worker.respond_to?(method) } raise "object from worker factory doesn't quack like a worker" end worker end |
#num_workers ⇒ Object
12 13 14 |
# File 'lib/breeder/breeding_strategy/threads.rb', line 12 def num_workers @threads.size end |
#reap! ⇒ Object
39 40 41 42 43 44 45 46 47 |
# File 'lib/breeder/breeding_strategy/threads.rb', line 39 def reap! if !@workers.empty? thread = @threads.pop worker = @workers.pop worker.stop! sleep 1 thread.kill end end |
#spawn! ⇒ Object
33 34 35 36 37 |
# File 'lib/breeder/breeding_strategy/threads.rb', line 33 def spawn! worker = create_worker @workers << worker @threads << Thread.new { worker.run } end |
#start! ⇒ Object
16 17 18 |
# File 'lib/breeder/breeding_strategy/threads.rb', line 16 def start! @initial_workers.times { spawn! } end |
#stop! ⇒ Object
20 21 22 |
# File 'lib/breeder/breeding_strategy/threads.rb', line 20 def stop! @workers.size.times { reap! } end |