去除 MPI_Bcast()

4

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

如何使用MPI_Send和MPI_Receive完成这个任务?

我以前从未使用过这些函数,不知道是否需要循环MPI_Receive以有效地发送所有内容。

在代码中,我已经标明了需要替换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;
}
2个回答

5
你需要使用 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);

3
如果要使用不同大小的块,请使用vscatter。 - haraldkl

3
如果您确实想使用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);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接