[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

waiting for multiple child processes to finish

Martin DeMello

11/13/2006 2:18:00 PM

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!"
-------------------------------------------------------------

1 Answer

Farrel Lifson

11/13/2006 2:31:00 PM

0

On 13/11/06, Martin DeMello <martindemello@gmail.com> wrote:
> 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