【问题标题】:Removing MPI_Bcast()删除 MPI_Bcast()
【发布时间】:2015-10-22 10:43:19
【问题描述】:

所以我有一些代码,我使用 MPI_Bcast 将信息从根节点发送到所有节点,但我想让我的 P0 将数组的块发送到各个进程。

如何使用 MPI_Send 和 MPI_Receive 执行此操作?

我以前从未使用过它们,我不知道是否需要循环我的 MPI_Receive 才能有效地发送所有内容或什么。

我已经在代码中放置了巨大的大写锁定 cmets,我需要替换我的 MPI_Bcast(),对于代码瀑布,提前抱歉。

代码:

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

#define MAXSIZE 10000000

int add(int *A, int low, int high)
{
  int res = 0, i;

  for(i=low; i<=high; i++)
    res += A[i];

  return(res);
}

int main(argc,argv)
int argc;
char *argv[];
{
    int myid, numprocs, x;
    int data[MAXSIZE];
    int i, low, high, myres, res;
    double elapsed_time;

    MPI_Init(&argc,&argv);
    MPI_Comm_size(MPI_COMM_WORLD,&numprocs);
    MPI_Comm_rank(MPI_COMM_WORLD,&myid);

        if (myid == 0)
          {
                for(i=0; i<MAXSIZE; i++)
                  data[i]=1;
          }

/* star the timer */
        elapsed_time = -MPI_Wtime();

//THIS IS WHERE I GET CONFUSED ABOUT MPI_SEND AND MPI_RECIEVE!!!
        MPI_Bcast(data, MAXSIZE, MPI_INT, 0, MPI_COMM_WORLD);

            x = MAXSIZE/numprocs;
            low = myid * x;
            high = low + x - 1;
        if (myid == numprocs - 1) 
        high = MAXSIZE-1;

            myres = add(data, low, high);
            printf("I got %d from %d\n", myres, myid);

        MPI_Reduce(&myres, &res, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
/* stop the timer*/
        elapsed_time += MPI_Wtime();

        if (myid == 0)
            printf("The sum is %d, time taken = %f.\n", res,elapsed_time);

    MPI_Barrier(MPI_COMM_WORLD);

            printf("The sum is %d at process %d.\n", res,myid);

    MPI_Finalize();
    return 0;
}

【问题讨论】:

    标签: mpi


    【解决方案1】:

    您需要MPI_Scatter。一个很好的介绍在这里:http://mpitutorial.com/tutorials/mpi-scatter-gather-and-allgather/

    我认为在您的代码中可能如下所示:

    elements_per_proc = MAXSIZE/numprocs;
    
    // Create a buffer that will hold a chunk of the global array
    int *data_chunk = malloc(sizeof(int) * elements_per_proc);
    
    MPI_Scatter(data, elements_per_proc, MPI_INT, data_chunk,
                elements_per_proc, MPI_INT, 0, MPI_COMM_WORLD);
    

    【讨论】:

    • 如果块有不同的大小,使用 vscatter。
    【解决方案2】:

    如果你真的想使用 MPI_Send 和 MPI_Recv,那么你可以使用这样的东西:

    int x = MAXSIZE / numprocs;
    int *procData = new int[x];
    
    if (rank == 0) {
        for (int i = 1; i < num; i++) {
            MPI_Send(data + i*x, x, MPI_INT, i, 0, MPI_COMM_WORLD);
        }
    } else {
        MPI_Recv(procData, x, MPI_INT, 0, 0, MPI_COMM_WORLD, &status);
    }
    

    【讨论】:

      猜你喜欢
      • 2012-11-20
      • 2013-11-30
      • 1970-01-01
      • 2012-06-16
      • 2012-11-05
      • 2011-10-21
      • 2017-01-25
      • 1970-01-01
      相关资源
      最近更新 更多