c - MPI_Scatter 和 MPI_Gather 不起作用

标签 c mpi

你好,我正在尝试使用 MPI 用 C 语言编写一个简单的并行程序。程序应该找到数组中的最大值。根进程应使用 MPI_Scatter 将数组 block 发送到所有进程,然后通过 MPI_Gather 收集结果。当我运行该程序时,我收到如下一般错误:

也许这个 Unix 错误消息会有所帮助: Unix 错误号:14 地址错误

我知道 MPI_Scatter 和 MPI_Gather 或我发送到此函数的值存在一些问题。

我试图找到解决方案,但没有找到任何有用的东西。

这是我的代码:

  #include <mpi.h>
  #include <stdio.h>
  #include <stdlib.h> 
  #define BUFSIZE 9

  int max(int *buf, int N){
      int i;
      int value = 0;
      for(i=0; i<N; i++){
         if (buf[i]>value){
             value = buf[i];
         }
      }
 return value;
 }
 int main(int argc, char** argv)
 { int size, rank;
   int slave;
   int *buf;
   int *buf1; 
   int *buf2;       
   int i, n, value;
   MPI_Status status;
   /* Initialize MPI  */
   MPI_Init(NULL, NULL);
   /* 
    * Determine size in the world group.
    */
   MPI_Comm_size(MPI_COMM_WORLD, &size);

   if ((BUFSIZE % size) != 0) {
     printf("Wrong Bufsize ");
     return(0);
   }


  MPI_Comm_rank(MPI_COMM_WORLD, &rank); 

  if (rank==0) { 
     buf = (int *)malloc(BUFSIZE*sizeof(int));
     buf2 = (int *)malloc(size*sizeof(int));

     printf("\n Generated array: \n");
     for(i=0; i<BUFSIZE; i++){
       buf[i] = rand() % 20;
       printf("%d, ", buf[i]);
     }
     printf("\n");
     printf("\n Sending values to processes:"); 
     printf("\n -----------------------------"); 
  }

  buf1 = (int *)malloc((BUFSIZE/size)*sizeof(int));

  MPI_Scatter(buf, BUFSIZE/size, MPI_INT, buf1, BUFSIZE/size, MPI_INT, 0, MPI_COMM_WORLD);

  value = max(&buf1[0], BUFSIZE/size);

  printf("\n Max from rocess %d : %d \n", rank, max(&buf1[0], BUFSIZE/size));

  MPI_Gather(&value, 1, MPI_INT, buf2, 1, MPI_INT, 0, MPI_COMM_WORLD);

  if (rank == 0){
     printf("\n Max value: %d", max(&buf2[0], size));
  }

  MPI_Finalize();
  return(0);
  }

最佳答案

将指针初始化为 NULL,并跟踪它们。 使用buf1代替&buf1[0],更清晰。 在 MPI_Finalize() 之前释放缓冲区:

if(bufferPionter != NULL) free(bufferPionter);

如果指针出现问题,就会在自由调用中崩溃。在 max 函数中,如果所有数字都小于零,则最大值为零。我解决了这个问题。

 int max(int *buf, int N){
      int i;
      int value = N? buf[0] : 0;
      for(i=0; i<N; i++){
         if (buf[i]>value){
             value = buf[i];
         }
      }
 return value;
 }

最诚挚的问候!

关于c - MPI_Scatter 和 MPI_Gather 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19407128/

相关文章:

c# - .NET MPI 实现?

c++ - 通过 MPI 发送和接收 2D 数组

c - C 中 getChar 循环的字符数限制

创建一个定义了 malloc_hook() 的 linux Shell

c++ - C 或 C++ 中的多态引擎

c - MPI 偶发错误

mpi - Mvapic2 缓冲区混叠

c - 位板到位板(三元位板)转换

c - 三重等于 C 中的有效运算符吗?

debugging - 使用 GDB 在 Fortran 中调试 MPI 程序(在 MAC 上)