I’m trying to dot product two vectors, with each process taking on a separate starting and ending index. What seems to be happening is that the code gets executed twice.
void DotProduct::MultiProcessDot()
{
pid_t pID,w;
int status;
unsigned int index = mNumberOfValuesPerVector / 2;
if((pID = fork()) < 0){
cout << "fork error" << endl;
}
else if(pID == 0){ /* child */
ProcessDotOperation(0, index);
exit(EXIT_FAILURE);
}
else{ /* parent */
ProcessDotOperation(index, mNumberOfValuesPerVector);
w = waitpid(pID, &status, WNOHANG);
if(w == 0){
cout << "alive" << endl;
}else if(w == -1){
cout << "dead" << endl;
}
}
}
ProcessDotOperation calculates the dot product using shared memory with sem_wait() and sem_post(). What seems to be happening is this:
-
Parent runs
ProcessDotOperation -
“alive” is printed
-
Parent runs
ProcessDotOperation -
“alive” is printed
-
Program continues execution (going on to other functions)
-
Child runs
ProcessDotOperation -
Child runs
ProcessDotOperation
Note: I may have a fundamental misunderstanding of what’s happening, so by parent and child, I’m referring to the comments in the code as to which process I think is running.
How do I make it such that the child runs ProcessDotOperation once, the parent runs ProcessDotOperation once, and then the program continues operation?
Any help is appreciated.
Edit
If I print before the fork(), and change w = waitpid(pID, &status, WNOHANG); to w = waitpid(pID, &status, 0);, here’s the output:
forking
parent
child
forking
parent
child
continued execution…
Here’s the code of ProcessDotOperation:
void DotProduct::ProcessDotOperation(unsigned int startIndex, unsigned int endIndex)
{
for(unsigned int i = startIndex; i < endIndex; i++){
sem_wait(mSem);
mShmProductId += mVectors[0][i] * mVectors[1][i];
cout << startIndex << " " << endIndex << " " << i << endl;
sem_post(mSem);
}
}
Someone is calling MultiProcessDot a second time.