我必须使用 P 处理器添加整数数组的元素。下面是我到目前为止编写的代码。我已经定义了一个数组和一些 4 个处理器来进行一些测试。
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
#define P 17
#define SIZE 153
static pid_t id[P];
static int elementsList[] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17
};
void getSubvectorSum(int elemList[], int start, int step, int size,int wPipe){
int sum = 0;
int i;
for(i = start; i < size; i += step){
sum += elemList[i];
}
write(wPipe,&sum,sizeof sum);
}
int main(){
int fd[2];
int total = 0;
int result;
int nbytes;
int i;
pipe(fd);
for(i = 0; i < P; i++){
id[i] = fork();
if(id[i] == 0){
close(fd[0]);
getSubvectorSum(elementsList,i,P,SIZE,fd[1]);
exit(0);
}
}
for(i = 0; i < P; i++){
wait(NULL);
}
close(fd[1];
for(i = 0; i < P; i++){
nbytes = read(fd[0],&result,sizeof result);
if(nbytes > 0){
printf("Something on the pipe.\n");
total += result;
} else {
printf("Nothing on the pipe.\n");
}
}
for(i = 0; i < P; i++){
kill(id[i],SIGKILL);
}
printf("total result: %d\n",total);
return 0;
}
我做的事情对吗?