user2864054
user2864054

Reputation: 31

How do I use MPI to scatter a 2d array?

I am trying to use MPI to distribute the work for bucket sort. When I scatter the array, I wanted each process to receive a single bucket (int array) and be able to print its content. However, my current program prints out incorrect values, which make me think I am not indexing into the memory I want. Can someone help explain how I can properly index into the array I am passing to each process or how I am doing this incorrectly?

#define MAX_VALUE 64
#define N 32
main(int argc, char *argv[]){

MPI_Init(&argc, &argv);  //initialize MPI environment
int** sendArray = malloc(16*sizeof(int *));
int *arrayIndex = (int *) malloc(16*sizeof(int));
int *receiveArray = (int *) malloc(N*sizeof(int));
int nps, myrank;
MPI_Comm_size(MPI_COMM_WORLD, &nps);
MPI_Comm_rank(MPI_COMM_WORLD, &myrank);
int i;

if(myrank == 0)
{
  //create an array that stores the number of values in each bucket
  for( i = 0; i < 16; i++){
    arrayIndex[i] = 0;
  }

  int bucket =0;
  int temp = 0;
  //creates an int array within each array index of sendArray
  for( i = 0; i < 16; i++){
    sendArray[i] =  (int *)malloc(N * sizeof(int));
  }
  //Create a random int array with values ranging from 0 to MAX_VALUE
  for(i = 0; i < N; i++){
    temp= rand() % MAX_VALUE;
    bucket = temp/4;
    printf("assigning %d to index [%d][%d]\n", temp, bucket, arrayIndex[bucket]);
    sendArray[bucket][arrayIndex[bucket]]= temp;
    arrayIndex[bucket] = arrayIndex[bucket] + 1;
  }

 MPI_Scatter(sendArray, 16, MPI_INT, receiveArray, N, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Bcast(arrayIndex, 16, MPI_INT, 0, MPI_COMM_WORLD);
printf("bucket %d has %d values\n", myrank, arrayIndex[myrank]);
for( i = 0; i < arrayIndex[myrank]; i++){
  printf("bucket %d index %d has value %d\n", myrank, i, receiveArray[i]);

}
}

Upvotes: 3

Views: 3637

Answers (1)

Dezi
Dezi

Reputation: 182

What you are trying to do doesn't work because MPI always sends only the data you point to. It does not follow the pointers in your sendArray.

In your example you could just make your SendArray bigger, namely 16 * N and put all your data into that continuous array. That way you have a one-dimensional array, but that should not be a Problem in the code you gave us because all buckets have the same length, so you can access element j from bucket i with sendArray[i * N + j].

Also, in most cases send_count should be equal to recv_count. In your case that would be N. The correct MPI call would be

MPI_Scatter(sendArray, N, MPI_INT, receiveArray, N, MPI_INT, 0, MPI_COMM_WORLD);

Upvotes: 2

Related Questions