Gilfoyle
Gilfoyle

Reputation: 3636

C: MPI_Allgather produces error

I first generate on every processor a random number. In the second step I want to send the generated numbers to every other processor. That is that after using MPI_Allgather every processor owns a list of all generated random numbers:

enter image description here

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

int main(int argc, char **argv){

    int nameLen;
    char processorName[MPI_MAX_PROCESSOR_NAME];

    int myrank;           // Rank of processor
    int numprocs;         // Number of processes
    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &myrank);
    MPI_Comm_size(MPI_COMM_WORLD, &numprocs);
    MPI_Get_processor_name(processorName,&nameLen);
    MPI_Status status;

    time_t t;
    srand((unsigned)time(NULL)+myrank*numprocs+nameLen);

    long c = rand()%100;

    printf("Processor %d has %li particles\n", myrank, c);

    long oldcount[numprocs];

    // Every processor gets the random number of the other processors
    MPI_Allgather(&c, 1, MPI_LONG, &oldcount, numprocs, MPI_LONG, MPI_COMM_WORLD);

    for(int i=0; i<numprocs; i++){
         printf("Processor %d: %d entry of list is %li\n", myrank, i, oldcount[i]);
    }

    MPI_Finalize();
    return 0;
}

This code produces an error. But why? I think I used MPI_Allgather the right way:

MPI_Allgather(
    void* send_data,
    int send_count,
    MPI_Datatype send_datatype,
    void* recv_data,
    int recv_count,
    MPI_Datatype recv_datatype,
    MPI_Comm communicator)

Upvotes: 1

Views: 92

Answers (1)

Roland W
Roland W

Reputation: 1461

The problem is with the recv_count parameter to MPI_Allgather. The MPI spec says that it specifies the "number of elements received from any process". You are giving the total number of elements. Try

MPI_Allgather(&c, 1, MPI_LONG, &oldcount, 1, MPI_LONG, MPI_COMM_WORLD);

Upvotes: 2

Related Questions