Class: ParallelWork::Runner

Inherits:
Object
  • Object
show all
Defined in:
lib/parallel_work/runner.rb

Constant Summary collapse

SOCKET_MAX_LEN =
1000
MESSAGE_LEN =
5

Instance Method Summary collapse

Constructor Details

#initialize(work, process_block) ⇒ Runner

Returns a new instance of Runner.

Parameters:

  • work (#next)


8
9
10
11
12
13
# File 'lib/parallel_work/runner.rb', line 8

def initialize work, process_block
  @work = work
  @process_block = process_block
  @master = nil
  @parent_sockets = []
end

Instance Method Details

#close_other_socketsObject



38
39
40
41
42
43
44
45
46
47
# File 'lib/parallel_work/runner.rb', line 38

def close_other_sockets
  if @master
    @child_socket.close
  else
    @parent_sockets.each do |socket|
      socket.close
    end
  end
  self
end

#setup_socketsObject



15
16
17
18
# File 'lib/parallel_work/runner.rb', line 15

def setup_sockets
  @child_socket, parent_socket = Socket.pair("AF_UNIX", "SOCK_DGRAM", 0)
  @parent_sockets << parent_socket
end

#spawn(n_workers) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/parallel_work/runner.rb', line 20

def spawn n_workers
  setup_sockets

  child_pid = fork
  if child_pid
    if n_workers == 1
      @master = true
    else
      @master = false
      spawn n_workers - 1
    end
  else
    @master = false
  end

  self
end

#startObject



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/parallel_work/runner.rb', line 49

def start
  if @master
    puts "master pid #{Process.pid}"
    its_over = false
    while !@parent_sockets.empty? && (ready = IO.select(@parent_sockets))
      socket = ready[0][0]
      message_from_worker = Messaging.recv socket
      send_quit = lambda do |socket|
        Messaging.send socket, Message::Quit.new
        socket.close
      end
      begin
        if its_over
          send_quit[socket]
        else
          Messaging.send socket, Message::Work.new(@work.next)
        end
      rescue StopIteration
        its_over = true
        send_quit[socket]
      end
      @parent_sockets = @parent_sockets.reject{|s|s.closed?}
    end
  else
    puts "child pid #{Process.pid}"
    Messaging.send @child_socket, Message::Ready.new
    while (message = Messaging.recv @child_socket)
      case message
        when Message::Work
          @process_block.call(message.payload)
          Messaging.send(@child_socket, Message::Ready.new)
        when Message::Quit
          exit 0
        else
          raise "unknown message #{message}"
      end
    end
  end
end