Sending an int array via MPI_Send

16,492

If you are going to dynamically allocate the array, the send and receive would be:

MPI_Send(array,10,MPI_INT,1,tag,MPI_COMM_WORLD);

and

MPI_Recv (array,10,MPI_INT,0,tag,MPI_COMM_WORLD,&status);

(Note that array is array and not &array)

As suggested in the comments, your understanding of MPI seems fine however refreshing your usage of C pointers may help.

Edit: As mentioned by Gilles, all processes receiving data into an array need to have memory allocated for them too. (Maybe send the size of the data first so the receiver knows how big to allocate the array? There are other ways to do this however that is a simple explanation)

Share:
16,492

Related videos on Youtube

John M.
Author by

John M.

Updated on June 04, 2022

Comments

  • John M.
    John M. almost 2 years

    I'm new to MPI and i would like to send an int array via MPI_Send to another process.

    // Code example
    
          int main(int argc, char ** argv)
          {
           int * array;
           int tag=1;
           int size;
           int rank;
           MPI_Status status;
           MPI_Init (&argc,&argv);
           MPI_Comm_size (MPI_COMM_WORLD,&size);
           MPI_Comm_rank (MPI_COMM_WORLD,&rank);
           if (rank == 0)
           {
             array = malloc (10 * sizeof(int)); // Array of 10 elements
             if (!array) // error checking
             {
              MPI_Abort (MPI_COMM_WORLD,1);
             }
           MPI_Send(&array,10,MPI_INT,1,tag,MPI_COMM_WORLD);
           }
           if (rank == 1)
           {
            MPI_Recv (&array,10,MPI_INT,0,tag,MPI_COMM_WORLD,&status);
            // more code here
           }
          MPI_Finalize();
    // More code here
    

    I would like to ask three things.

    1. Is this a SAFE way to send an array to another process-rank?
    2. Is this a syntax wise correct usage of MPI_Send() and MPI_Recv()?
    3. Is there a better way to send and receive an array without too much trouble?

    Any help is appreciated.

    • Zulan
      Zulan over 5 years
      I would recommend to revisit the basics about pointers in C before jumping in MPI.
    • Gilles Gouaillardet
      Gilles Gouaillardet over 5 years
      MPI_Recv() does not allocate the array for you. both MPI_Send() and MPI_Recv() needs a pointer to the data, and not the address of a pointer to the data.
  • Gilles Gouaillardet
    Gilles Gouaillardet over 5 years
    array must be allocated on the receiver too!
  • HCF3301
    HCF3301 over 5 years
    Good shout Gilles!