我正在尝试用字符串实现Odd-Even转置排序,解决MPI没有字符串定义这一事实。
#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();
}
我遇到了MPI_Gather和Scatter的问题,当array
和value
是整数时,它可以正常工作,对字符串不起作用。
当我尝试编译并运行时,我收到以下错误
*** Error in `./P2': munmap_chunk(): invalid pointer: 0x00007ffe3ec5e020***
*** Error in `./P2': free(): invalid pointer: 0x00007fff38dc3ec5 ***