1

I am trying to do sort key-value pairs with qsort. Every proc reads in files with filenames as the proc ids. MPI_Gather sends all the read values to proc 0, which sorts the keys and stores the key-val pairs in a file called "Output". The gather however, does not seem to work. Any help is appreciated. Thanks!

I run the code as

  mpirun -np 3 ./a.out

and my input files are: File "0":

21 bbbb  
2119 iiii
120 hhhh

File "1":

40 dddd 
10 aaaa
100 gggg

File "2":

32 cccc
44 eeee
99 ffff

And the code is:

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

#define BUFSIZE 3
#define BUFLEN 255

struct keyval{
int key;
char val[BUFLEN];
};

typedef struct keyval keyval_s;

typedef int (*compareptr)(const void*, const void*);

int compare (keyval_s * a, keyval_s * b)
{
  return ( a->key - b->key );
}

int main (int argc, char *argv[])
{    
  int values[BUFSIZE];
  keyval_s kv[BUFSIZE], *recv;
  int n, i=0, temp;
  FILE *in, *out;

  int rank, size;
  MPI_Init(&argc, &argv);
  MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  MPI_Comm_size(MPI_COMM_WORLD, &size);
  char filename[20];
  char data[20];

  if(rank ==0){
recv = (keyval_s *) malloc (size*BUFSIZE*sizeof(keyval_s));
   }

  sprintf(filename, "%d", rank);
  in=fopen(filename,"r");
  while(fscanf(in,"%d %s",&kv[i].key, kv[i].val) != EOF){
printf("Read key %d, data %s from file\n", kv[i].key, kv[i].val);   
i++;
  }
  MPI_Gather(kv,BUFSIZE,MPI_BYTE,recv,BUFSIZE,MPI_BYTE,0,MPI_COMM_WORLD);
  if(rank==0){
 qsort ((void*)&kv, BUFSIZE, sizeof(keyval_s),(compareptr) compare);
 out=fopen("Output","w");
 for (n=0; n<BUFSIZE*size; n++)
    fprintf (out,"%d %s\n",recv[n].key, recv[n].val);
free(recv);
fclose(out);
   }
fclose(in);
return 0;   
}

1 Answer 1

1

The size of the data in MPI_Gather is incorrect. It should be

MPI_Gather(kv, 
           sizeof(keyval_s)*BUFSIZE, 
           MPI_BYTE,
           recv, 
           sizeof(keyval_s)*BUFSIZE, 
           MPI_BYTE, 
           0, 
           MPI_COMM_WORLD);

Note that the recvcount parameter in MPI_Gather is for a message from a single rank, not the total size of the gathered data.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.