Class: Breeder::BreedingStrategy::Forks

Inherits:
Object
  • Object
show all
Defined in:
lib/breeder/breeding_strategy/forks.rb

Instance Method Summary collapse

Constructor Details

#initialize(worker_factory, initial_workers) ⇒ Forks

Returns a new instance of Forks.



5
6
7
8
9
# File 'lib/breeder/breeding_strategy/forks.rb', line 5

def initialize(worker_factory, initial_workers)
  @children = []
  @worker_factory = worker_factory
  @initial_workers = initial_workers
end

Instance Method Details

#create_workerObject



23
24
25
26
27
28
29
30
# File 'lib/breeder/breeding_strategy/forks.rb', line 23

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_workersObject



11
12
13
# File 'lib/breeder/breeding_strategy/forks.rb', line 11

def num_workers
  @children.size
end

#reap!Object



51
52
53
54
55
56
57
58
# File 'lib/breeder/breeding_strategy/forks.rb', line 51

def reap!
  if !@children.empty?
    pid = @children.pop
    Process.kill('HUP', pid)
    sleep 1
    Process.kill(9, pid)
  end
end

#spawn!Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/breeder/breeding_strategy/forks.rb', line 32

def spawn!
  t = Thread.new do
    if pid = Process.fork
      #parent
      @children << pid
    else
      worker = create_worker
      #child
      trap('HUP') do
        worker.stop!
      end
      trap('INT', 'DEFAULT')
      worker.run
      Process.exit
    end
  end
  t.join
end

#start!Object



15
16
17
# File 'lib/breeder/breeding_strategy/forks.rb', line 15

def start!
  @initial_workers.times { spawn! }
end

#stop!Object



19
20
21
# File 'lib/breeder/breeding_strategy/forks.rb', line 19

def stop!
  @children.size.times { reap! }
end