MPI聚集和qsort

时间:2011-10-22 05:16:13

标签: c mpi

我正在尝试做一个简单的排序,其中每个非零proc将文件(filename = proc#)读入缓冲区。零proc收集所有这些bufs,对其进行排序然后将其打印出来。但是,在下面的代码中,proc 0收集proc1的缓冲区,但不收集proc 2的缓冲区。有什么建议吗?

我用mpirun -np 3 a.out

执行它

我的输入文件是 文件名:“1” 40 10 100

文件名:“2” 90 20 25

,代码是:

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

#define DEBUG 1

//#undef DEBUG


int compare (const void * a, const void * b)
{
   return ( *(int*)a - *(int*)b );
}

int main (int argc, char *argv[])
{
int values[3];
int recv[3];
int n, i=0, temp;
FILE *in1, *in2;
int rank, size;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
char filename[20];
if(rank!=0){
      // read files with filename"<proc#>" into the buffer
      sprintf(filename, "%d", rank);
      in1=fopen(filename,"r");
      while(fscanf(in1,"%d",&values[i]) != EOF){
            printf("rank %d Read data %d\n", rank,values[i]);
            i++;
      }
 }
 // gather values from all procs.

 MPI_Gather(values,i,MPI_INT,recv,i,MPI_INT,0,MPI_COMM_WORLD);
 printf("Gather done!");
if(rank==0){


    // sort
    qsort (recv, 6, sizeof(int), compare);
    // print results
    for (n=0; n<6; n++)
            printf ("%d ",recv[n]);
    printf("\n");
 }

 if(rank!=0)
    fclose(in1);
 MPI_Finalize();
 return 0;
}

1 个答案:

答案 0 :(得分:2)

int recv[3];

接收缓冲区的大小应该是要在收集节点上收集的所有处理器的元素总数。 所以recv [9]应该在这里工作。

结帐这个例子进行收集 example