1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
|
#include "stdafx.h"
#include "mpi.h"
#include <iostream>
#include <fstream>
#include <string>
#include <cctype>
#include <cstring>
#include <cstdlib>
#include <ctime>
using namespace std;
int main(int argc, char** argv) {
int rank, size, tag = 0;
ofstream outfile;
ifstream infile;
bool read = false;
const int max = 10;
char message[max]; char msgS[max]; char msgR[max];
MPI_Status stat;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
// Check all Processors are alive
cout << "Initialised processor: " << rank << endl;
MPI_Barrier(MPI_COMM_WORLD); // naughty, but just for debugging
if (rank == 0) {
outfile.open("in.txt");
cout << "Processor " << rank << " is asking for messages (stop to finish)\n";
do {
cin.getline(message, max);
if (strcmp(message, "stop") == 0) break;
outfile << message << endl;
} while (strcmp(message, "stop") != 0);
cout << "Messages written to file [in.txt]!" << endl;
outfile.close();
}
MPI_Barrier(MPI_COMM_WORLD); // naughty, but just for debugging
if (rank == 0) {
int count = 0;
infile.open("in.txt");
while (infile >> msgS) {
MPI_Send(msgS, max, MPI_CHAR, 1, 1, MPI_COMM_WORLD);
cout << "Rank " << rank << " sent message " << msgS << endl;
count++;
}
MPI_Send(&count, 1, MPI_INT, 1, 2, MPI_COMM_WORLD);
}
else if (rank == 1) {
int count1;
outfile.open("out.txt");
MPI_Recv(&count1, 1, MPI_INT, 0, 2, MPI_COMM_WORLD, &stat);
do {
MPI_Recv(msgR, max, MPI_CHAR, 0, 1, MPI_COMM_WORLD, &stat);
cout << "Rank " << rank << " received message " << msgR << endl;
outfile << msgR << endl;
count1--;
} while (count1 != 0);
}
else {
cout << "Rank " << rank << " on standby" << endl;
}
infile.close();
outfile.close();
MPI_Finalize();
return 0;
}
|