waiting for multiple child processes to finish

M

Martin DeMello

Why does this not work (it waits for each process to finish before
launching the next):
-------------------------------------------------------------
$stdout.sync = true

10.times {|i|
pid = Process.fork {
puts "launching process #{i}"
3.times {
sleep 0.5
puts "hello from process #{i}"
}
}
Thread.new { Process.waitpid(pid) }.join
}

puts "done!"
-------------------------------------------------------------

but this does:
-------------------------------------------------------------
$stdout.sync = true

pids = []
10.times {|i|
pids << Process.fork {
puts "launching process #{i}"
3.times {
sleep 0.5
puts "hello from process #{i}"
}
}
}

pids.each {|pid| Thread.new { Process.waitpid(pid) }.join }
puts "done!"
-------------------------------------------------------------
 
F

Farrel Lifson

Why does this not work (it waits for each process to finish before
launching the next):
-------------------------------------------------------------
$stdout.sync = true

10.times {|i|
pid = Process.fork {
puts "launching process #{i}"
3.times {
sleep 0.5
puts "hello from process #{i}"
}
}
Thread.new { Process.waitpid(pid) }.join
}

puts "done!"
-------------------------------------------------------------

but this does:
-------------------------------------------------------------
$stdout.sync = true

pids = []
10.times {|i|
pids << Process.fork {
puts "launching process #{i}"
3.times {
sleep 0.5
puts "hello from process #{i}"
}
}
}

pids.each {|pid| Thread.new { Process.waitpid(pid) }.join }
puts "done!"
-------------------------------------------------------------

The join in the first solution forces the thread (and forked process)
to finish before continuing onto starting the next fork. In the second
solution all the processes are forked first before waiting. You can
probably rewrite that last loop simply as:
pids.each{|pid| Process.waitpid(pid)}

Farrel
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,731
Messages
2,569,432
Members
44,834
Latest member
BuyCannaLabsCBD

Latest Threads

Top