我试图点产品两个向量,每个进程采取单独的开始和结束索引。似乎正在发生的是代码被执行两次。叉子和父母运行单独的代码
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
计算使用共享存储器与sem_wait()
和sem_post()
点积。什么似乎发生是这样的:
父运行
ProcessDotOperation
“活着” 打印
父运行
ProcessDotOperation
“活着” 打印
程序继续执行(继续执行其他功能)
儿童运行
ProcessDotOperation
儿童运行
ProcessDotOperation
注:我可能会发生的事情的一个根本性的误解,因此通过parent
和child
,我指的是在评论关于我认为正在运行哪个进程的代码。
我该如何让孩子运行一次ProcessDotOperation
一次,父母运行ProcessDotOperation
一次,然后程序继续运行?
任何帮助表示赞赏。
编辑
如果我的fork()
之前打印,并更改w = waitpid(pID, &status, WNOHANG);
到w = waitpid(pID, &status, 0);
,这里的输出:
分叉
父
孩子
分叉
父
孩子
继续执行...
这里是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);
}
}
您对fork()的工作方式的理解完全正确。你显示的代码应该做你想要的。关于调试,您需要完成游戏。尝试在调用fork()之前打印一行。尝试从'ProcessDotOperation'内打印参数和'getpid()'的值。尝试在wait()调用之前打印'pID'的值。 – 2012-03-29 01:53:21
'ProcessDotOperation'的代码是什么? – JaredPar 2012-03-29 01:53:37
* Aside *:考虑使用['std :: thread'](http://en.cppreference.com/w/cpp/thread/thread)而不是'fork()'和共享内存。 – 2012-03-29 01:56:05