I’m in trouble trying to make this code to work. What I’m trying to do is to make my program to calculate some specific algorithm in parallel. Some times it works, some time is doesn’t. This happens often when I run it with big numbers, but I can see in top (linux command) a lot of defunct processes and I think this happen because my forks are ending asyncronous and some childs are being left behind. But I thought in the beginning that my logic was at least making possible to finish all the calculations because I’ve set 2 control vars, flags and alldone, which are both shared memory space and are used to finish the while loop. I’ve been searching for some light and now I come here to ask for help since I can’t find something that would help me. Can anyone help me with my logical problem in the following code in some way that my processes can be finished in the right sequence avoiding lefting defunct process behind? Thanks in advance!
for(i=0;i<numforks*sizeof(int);i++)
flags[i] = 0;
*alldone = numforks;
pid = fork();
if(pid==0) {
pid1 = fork();
pid2 = fork();
pid3 = fork();
#ifdef DEBUG_F
printf("worker process\n");
#endif
do {
thisfork = thisfork -1;
if( flags[thisfork] == 0){
flags[thisfork] = 1;
#ifdef DEBUG_THREADS
printf("flags[%d] was zero now is %d\n", thisfork, flags[thisfork]);
#endif
if(thisfork == 7) {
heme(0,riall,chunk_size,r,pp,qq);
(*alldone)--;
}
if(thisfork == 6) {
heme(chunk_size,riall,chunk_size*2,r,pp,qq);
(*alldone)--;
}
if(thisfork == 5) {
heme(chunk_size*2,riall,chunk_size*3,r,pp,qq);
(*alldone)--;
}
if(thisfork == 4) {
heme(chunk_size*3,riall,chunk_size*4,r,pp,qq);
(*alldone)--;
}
if(thisfork == 3) {
heme(chunk_size*4,riall,chunk_size*5,r,pp,qq);
(*alldone)--;
}
if(thisfork == 2) {
heme(chunk_size*5,riall,chunk_size*6,r,pp,qq);
(*alldone)--;
}
if(thisfork == 1) {
heme(chunk_size*6,riall,chunk_size*7,r,pp,qq);
(*alldone)--;
}
if(thisfork == 0) {
heme(chunk_size*7,riall,chunk_size*8,r,pp,qq);
(*alldone)--;
}
}
} while( thisfork > 0 && alldone > 0 );
exit(0);
} else {
wait(&stat);
}
If
alldoneis in shared memory, then you need to apply atomic decrement. Otherwise, youralldonecounter can be left in an inconsistent state. If you are using GCC, you can use a builtin to do the decrement.