Добавил:
Upload
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз:
Предмет:
Файл:MPIprograms / main2
.cpp#include <iostream>
#include "mpi.h"
int main( int argc, char **argv ) {
using std::cin; using std::cout; using std::endl;
int flag; MPI_Initialized(&flag);
if ( !flag ) MPI_Init( &argc, &argv );
int myrank; MPI_Comm_rank( MPI_COMM_WORLD, &myrank );
int commsize; MPI_Comm_size( MPI_COMM_WORLD, &commsize );
if ( myrank == 0 ) {
MPI_Status *statuses = new MPI_Status[commsize-1];
MPI_Request *requests = new MPI_Request[commsize-1];
char *source = new char[commsize*256];
char *dest = new char[commsize*256];
for ( int i = 1; i < commsize; i++ ) {
cout << "Process 0: what to send to process " << i << "? ";
cin >> &source[i*256];
}
for ( int i = 1; i < commsize; i++ )
MPI_Isend( &source[i*256], strlen( &source[i*256] )+1, MPI_CHAR, i, 0, MPI_COMM_WORLD, &requests[i-1] );
MPI_Waitall( commsize-1, requests, statuses );
cout << "Process 0 has sent all messages\n";
for ( int i = 1; i < commsize; i++ )
MPI_Irecv( &dest[i*256], 256, MPI_CHAR, i, 0, MPI_COMM_WORLD, &requests[i-1] );
MPI_Waitall( commsize-1, requests, statuses );
cout << "Process 0 has received:\n";
for ( int i = 1; i < commsize; i++ )
cout << &dest[i*256] << " from process " << i << endl;
}
else {
MPI_Status status;
MPI_Request request;
char source[256];
char dest[256];
MPI_Recv( dest, 256, MPI_CHAR, 0, 0, MPI_COMM_WORLD, &status );
cout << "Process " << myrank << " has received " << dest << endl;
itoa( myrank, source, 10 ); strcat( dest, " " ); strcat( dest, source );
MPI_Isend( dest, strlen( dest )+1, MPI_CHAR, 0, 0, MPI_COMM_WORLD, &request );
cout << "Process " << myrank << " has sent " << dest << endl;
}
MPI_Finalize();
return 0;
}