简体   繁体   English

如何使用P处理器计算整数数组的元素之和

[英]How to calculate the sum of the elements of an array of integers using P processors

I have to add the elements of an array of integers using P processors. 我必须使用P处理器添加整数数组的元素。 Below it's the code i've written so far. 下面是我到目前为止编写的代码。 I have defined an array and a number of 4 processors to can make some tests. 我定义了一个数组和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;

}

Am I doing things right? 我做对了吗?

You program might deadlock with large number of processes: once the pipe buffer is full, children will block on write() while the parent will wait() . 您的程序可能会死于大量进程:一旦管道缓冲区已满,子进程将在write()上阻塞,而父进程将在wait()上阻塞。 Drain the pipe in the parent without waiting for the child processes to complete. 排空父管道中的管道,而无需等待子进程完成。

Your program might read less bytes than written by children. 您的程序读取的字节数可能少于孩子写入的字节数。

Check error conditions of system calls. 检查系统调用的错误情况。 It might make it easier to uncover bugs. 这可能会更容易发现错误。

I'm not sure but you might need to retry wait() call on EINTR error; 我不确定,但是您可能需要重试EINTR错误的wait()调用; otherwise you'll create zombies. 否则,您将创建僵尸。

You shouldn't need to kill . 你不需要kill

Look at parallel-sum-fork.c and parallel-sum-openmp.c for comparison. 查看parallel-sum-fork.cparallel-sum-openmp.c进行比较。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM