cirval
cirval

Reputation: 69

MPI_scatter of 1D array

I new to MPI and I am trying to write program that uses MPI_scatter. I have 4 nodes(0, 1, 2, 3). Node0 is master, others are slaves. Master asks user for number of elements of array to send to slaves. Then it creates array of size number of elements * 4. Then every node prints it`s results.

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

#define MASTER 0

int main(int argc, char **argv) {
   int id, nproc, len, numberE, i, sizeArray;
   int *arrayN=NULL;
   int arrayNlocal[sizeArray];

   MPI_Init(&argc, &argv);
   MPI_Comm_size(MPI_COMM_WORLD, &size);
   MPI_Comm_rank(MPI_COMM_WORLD, &rank);

   if (id == MASTER){
     printf("Enter number of elements: ");
     scanf("%d", &numberE);
     sizeArray = numberE * 4;
     arrayN = malloc(numberE * sizeof(int));
     for (i = 0; i < sizeArray; i++){
       arrayN[i] = i + 1;
     }
   }
   MPI_Scatter(arrayN, numberE, MPI_INT, &arrayNlocal, numberE,MPI_INT, MPI_COMM_WORLD);
   printf("Node %d has: ", id);
   for (i = 0; i < numberE; i++){ 
     printf("%d ",arrayNlocal[i]);
   }
   MPI_Finalize();
   return 0;
}

And as error i get:

BAD TERMINATION OF ONE OF YOUR APPLICATION PROCESSES
PID 9278 RUNNING AT 192.168.100.100
EXIT CODE: 139
CLEANING UP REMAINING PROCESSES
YOU CAN IGNORE THE BELOW CLEANUP MESSAGES

Upvotes: 1

Views: 2220

Answers (1)

francis
francis

Reputation: 9817

  • In arrayNlocal[sizeArray];, sizeArray is not initialized. The best way to go is to broadcast numberE to every processes and allocate memory for arrayNlocal. Something like:

    MPI_Bcast( &numberE, 1, MPI_Int, 0, MPI_COMM_WORLD)
    
  • arrayN is an array of size sizeArray = numberE * 4, so:

    arrayN = malloc(sizeArray * sizeof(int));
    
  • MPI_Scatter() needs pointers to the data to be sent on root node, and a pointer to receive buffer on each process of the communicator. Since arrayNlocal is an array:

     MPI_Scatter(arrayN, numberE, MPI_INT, arrayNlocal, numberE,MPI_INT,MASTER, MPI_COMM_WORLD);
    

or alternatively:

    MPI_Scatter(arrayN, numberE, MPI_INT, &arrayNlocal[0], numberE,MPI_INT,MASTER, MPI_COMM_WORLD);
  • id is not initialized in id == MASTER: it must be rank==MASTER.

As is, the prints at the end might occur in a mixed way between processes. Try to compile your code using mpicc main.c -o main -Wall to enable all warnings: it can save you a few hours in the near future!

Upvotes: 1

Related Questions