如何将2D表中的所有整数相加?

时间:2019-01-26 16:23:20

标签: c linux parallel-processing mpi

我有一个2D表,里面充满了整数,我想从下往上添加整数。每列的加法将存储在该列的第一行,最后将存储在表的第一行的整数相加并得出总和。如何知道分散后的数据去向,以及如何进行所需的添加?

#include <stdio.h>
#include <stdlib.h>
#include "mpi.h"

main(int argc, char *argv[]){
int up,down,left,right; 
int ndims=2;
int p,my_rank,my_cart_rank; 
MPI_Comm comm2D;
int dims[ndims],coord[ndims];
int wrap_around[ndims];
int reorder,nrows,ncols;
int **numbers;
int i,j,l,workload;


/* start up initial MPI environment */
MPI_Init(&argc, &arg
MPI_Comm_size(MPI_COMM_WORLD, &p);
MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);


/* process command line arguments*/
if (argc == 3) {
    nrows = atoi (argv[1]); ncols = atoi (argv[2]);
    dims[0] = nrows; /* number of rows */
    dims[1] = ncols; /* number of columns */
if( (nrows*ncols) != p)  {
if( my_rank ==0)
    printf("ERROR: nrows*ncols)=%d * %d = %d != p\n",nrows, ncols, nrows*ncols,p); 
MPI_Finalize();
exit(0);
  }
}

 if(my_rank == 0){
printf("flag");
        int k;                                                                
        int **numbers;
        numbers=(int **)malloc(nrows*sizeof(int *));    //allocating table to send it to the processes
            if( numbers == NULL ){
                printf("Not enough memory.The programm will be terminated.");
                exit(12);
            }
            for(k=0; k<ncols;k++){
                numbers[k]=(int *)malloc(ncols*sizeof(int));
                if(numbers[k]==NULL){
                    printf("Not enough memory.The programm will be terminated.");
                    exit(18);
                }
            }  
for(i=0;i<nrows;i++){       //filling allocated table with integers 
        for(j=0;j<ncols;j++){
            printf("numbers[%d][%d]= ",i,j);
            scanf("%d",&numbers[i][j]);
        l++;
        }
    } 
workload=l/p;   //calculating the amount of the table which will be     sent to each process
int *procrow=malloc (sizeof (int) *workload);   //1D table which is sent to each process with the calculated woekload
MPI_Scatter(numbers,workload,MPI_INT,procrow,workload,MPI_INT,0,MPI_COMM_WORLD); //scattering the table to the process
}


wrap_around[0] = wrap_around[1] = 0;
reorder = 1;
MPI_Cart_create(MPI_COMM_WORLD, ndims, dims,wrap_around, reorder, &comm2D); //create cartesian mapping
MPI_Cart_coords(comm2D, my_rank, ndims, coord); //find coordinations for each process
MPI_Cart_rank(comm2D, coord, &my_cart_rank); //using coords to find rank



MPI_Finalize();
}//main bracket

0 个答案:

没有答案