I have this code:
require 'pp'
$pool = []
def work arg
$pool.push($$)
sleep (1 + rand(5))
$pool.delete($$)
exit
end
ary = []
100.times { |x| ary.push(x) }
while ary.any? do
while $pool.size < 10 && ary.any?
arg = ary.pop
Process.detach( fork { work(arg) } )
pp $pool.size
sleep 0.01
end
end
for me it’s unexpected when I am filling $pool in work() pp $pool.size in second while loop always 0
where am I wrong?
When you create a new process with fork the new process gets a copy of the (empty) $pool. The $pool in the parent process which executes the loop is never populated with anything (the call to work function is executed in the child process), so it’s size is always 0.