我的代码有问题,这是我第一次使用 fork。一旦我使用管道或 vfork,我的子处理器就会串联而不是并联。我得到了我预期的答案,但程序没有做我想要的。
我的基本程序只计算 1 到 100000000、1+2+3+4...10000 等的总和。
我只是想学习分叉和管道并对其进行基准测试。
这是我的代码,对于混乱的代码和我的评论感到抱歉。这是我的测试代码,所以我弄得一团糟。
#include <iostream>
#include <ctime>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <csignal>
#include <cstdlib>
#include <fstream>
#include <fcntl.h>
#include <string.h>
using namespace std;
int main () {
long sumTemp =0;
long sum = 0;
long times = 1000000000; // number to add up
int threads = 4;
long amount[threads];
pid_t childPids[threads];
pid_t p;
time_t tstart, tend;
long lastNumber=0;
long addedValue =0;
int fd[2];
long readbuffer = 0;
int number = 0;
// Counting time
tstart = time(0);
for (int p=0; p<=threads; p++){
amount[p]=0;
}
//Having the task divided to threads
long divided = (times/threads);
for (int j=1; j<=threads; j++){
addedValue += divided;
amount[j]= addedValue;
cout << amount[j-1] << " .... " << j << " ... " << amount[j] << endl;
}
// Child making
for (int j=0; j<threads; j++){
// running fork
pipe(fd);
p = vfork();
if (p== -1)
{
printf("Error occoured with fork()\n");
exit(99); // exit status 99
}
else if (p == 0){
//calculation
cout << " child : " << j << " " << p <<endl;
for (long i=(amount[j]+1); i<=amount[j+1]; i++){
sumTemp += i;
}
exit(0);
}
else {
childPids[j] = p;
sum = sumTemp;
}
}
for(int k = 0; k < threads; k++){
waitpid(childPids[k], NULL, WNOHANG);
}
tend = time(0);
cout << endl << " Sum of adding " << times << "." << endl;
cout << " Sum : " << sum << endl;
cout << " It took " << difftime(tend, tstart) << " second(s)."
<< endl << endl;
}
`