I would like to make a section of my code more efficient. I'm thinking of making it fork off into multiple processes and have them execute 50/100 times at once, instead of just once.
For example (pseudo):
for line in file;
do
foo;
foo2;
foo3;
done
I would like this for loop to run multiple times. I know this can be done with forking. Would it look something like this?
while(x <= 50)
parent(child pid)
{
fork child()
}
child
{
do
foo; foo2; foo3;
done
return child_pid()
}
Or am I thinking about this the wrong way?
Thanks!
I don't like using
wait
because it gets blocked until the process exits, which is not ideal when there are multiple process to wait on as I can't get a status update until the current process is done. I prefer to use a combination ofkill -0
andsleep
to this.Given an array of
pids
to wait on, I use the belowwaitPids()
function to get a continuous feedback on what pids are still pending to finish.When I start a process in the background, I add its pid immediately to the
pids
array by using this below utility function:Here is a sample that shows how to use:
And here is how the feedback looks:
haridsv's approach is great, it gives the flexibility to run a processor slots setup where a number of processes can be kept running with new jobs submitting as jobs complete, keeping the overall load up. Here are my mods to haridsv's code for an n-slot processor for a 'grid' of ngrid 'jobs' ( I use it for grids of simulation models ) Followed by test output for 8 jobs 3 at a time, with running totals of running, submitted, completed and remaining
Test output: