我試圖點產品兩個向量,每個進程採取單獨的開始和結束索引。似乎正在發生的是代碼被執行兩次。叉子和父母運行單獨的代碼
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