Odd-Even Transposition Sort with Strings MPI C++

2019-08-20 03:44发布

问题:

I'm trying to implement an Odd-Even transposition sort with strings, working around the fact that MPI doesn't have a definition for strings.

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include <string>
#include <mpi/mpi.h>

const int MAX = 2;

using namespace std;

 int main(int argc, char **argv) {
  int rank, size;
  MPI_Status status;


  string array[MAX] = {"foobar1","foobar2"} ;
  int i, count;
  int A, B;
  string value[MAX];
  double startTime, endTime;

  srand(time(NULL));


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


  if(rank == 0) {
  startTime = MPI_Wtime();
  cout << endl;
  }

  MPI_Scatter(array, MAX, MPI_CHAR, value, MAX, MPI_CHAR, 0, MPI_COMM_WORLD);


  for(i = 0; i < size; i++) {

    if (i % 2 == 0) //even-step
    {
          if(rank % 2 == 0) //if even processes
          {
            MPI_Send(&value[0],1,MPI_CHAR,rank+1,0,MPI_COMM_WORLD);
            MPI_Recv(&value[1],1,MPI_CHAR,rank+1,0,MPI_COMM_WORLD,&status);

            if(value[1] < value[0]) {
              value[0] = value[1];
            }
          }
          else // is odd process
          {
            MPI_Recv(&value[1],1,MPI_CHAR,rank-1,0,MPI_COMM_WORLD,&status);
            MPI_Send(&value[0],1,MPI_CHAR,rank-1,0,MPI_COMM_WORLD);

            if(value[1]>value[0]) {
              value[0] = value[1];
            }
          }
    }
    else { //odd-step
            if((rank%2 == 1) && (rank != (size-1))) { 
            MPI_Send(&value[0],1,MPI_CHAR,rank+1,0,MPI_COMM_WORLD);
            MPI_Recv(&value[1],1,MPI_CHAR,rank+1,0,MPI_COMM_WORLD,&status);

            if(value[1]<value[0]) {
              value[0] = value[1];
            }
            }
          else if(rank != 0 && rank != (size-1)) {
           MPI_Recv(&value[1],1,MPI_CHAR,rank-1,0,MPI_COMM_WORLD,&status);
           MPI_Send(&value[0],1,MPI_CHAR,rank-1,0,MPI_COMM_WORLD);

          if(value[1]>value[0]) {
          value[0] = value[1];
              }
            }
       }
  }


  MPI_Gather(&value,size,MPI_CHAR,&array,size,MPI_CHAR,0,MPI_COMM_WORLD);


  if(rank == 0) {
      endTime = MPI_Wtime();
      cout << "Total Time:" << endTime-startTime << endl;
      cout << "Size of array:" << size << endl;
      cout << "String: ";
      for (int i = 0; i < size; i++)
      cout << " " << array[i] << endl;
      cout << endl;
  }

  MPI_Finalize();
}

I'm having an issue with the MPI_Gather and Scatter, it works just fine when array and value are integers, doesn't quite work with strings.

When I try to compile and run, I get the following errors

*** Error in `./P2': munmap_chunk(): invalid pointer: 0x00007ffe3ec5e020***
*** Error in `./P2': free(): invalid pointer: 0x00007fff38dc3ec5 ***
标签: c++ mpi mpich