这是第一次使用聚集/分散集体的人们的一个常见问题;在发送和接收计数中,您指定要发送到或从每个进程收到的项目的计数。因此,尽管确实如此,如果P
是处理器的数量,那么总共会得到P
项目,但这不是您为收集操作指定的项目;您指定您发送的计数为1,并且接收计数为1(来自每个进程)。像这样:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <mpi.h>
int main (int argc, char **argv) {
int rank;
int size;
int lvotes;
int *gvotes;
MPI_Init (&argc, &argv);
MPI_Comm_rank (MPI_COMM_WORLD, &rank);
MPI_Comm_size (MPI_COMM_WORLD, &size);
if (rank == 0)
gvotes = malloc(size * sizeof(int));
/* everyone sets their first lvotes element */
lvotes = rank+4;
/* Gather to process 0 */
MPI_Gather(&lvotes, 1, MPI_INT, /* send 1 int from lvotes.. */
gvotes, 1, MPI_INT, /* gather 1 int each process into lvotes */
0, MPI_COMM_WORLD); /* ... to root process 0 */
printf("P%d: %d\n", rank, lvotes);
if (rank == 0) {
printf("P%d: Gathered ", rank);
for (int i=0; i<size; i++)
printf("%d ", gvotes[i]);
printf("\n");
}
if (rank == 0)
free(gvotes);
MPI_Finalize();
return 0;
}
运行提供了
$ mpirun -np 3 ./gather
P1: 5
P2: 6
P0: 4
P0: Gathered 4 5 6