#include "stdafx.h"
#include <mpi.h>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <string>
#include <cctype>
#include <cstdlib>
#include <ctime>
#include <cctype>
#include <cstdlib>
#include <ctime>
using namespace std;
int randomize() {
srand(time(0));
int i = 1 + rand() % 3;
return i;
}
int main(int argc, char** argv) {
MPI_Init(&argc, &argv);
int rank, size, tag = 1;
ofstream outfile;
ifstream infile;
bool read = true;
const int max = 10;
char message[max]; char msgS[max]; char msgR[max];
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
outfile.open("in.txt");
cout << "Write messages: " << rank << endl;
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();
infile.open("in.txt");
outfile.open("out.txt");
if (rank == 0 && read) {
int i = randomize();
if (!infile.eof()) {
infile >> msgS;
MPI_Send(msgS, strlen(msgS), MPI_CHAR, (rank + i), tag, MPI_COMM_WORLD);
read = false;
}
else {
cout << "Messages written to file [out.txt]!" << endl;
infile.close();
outfile.close();
exit(0);
}
}
else if (rank == 1 && !read) {
MPI_Recv(msgR, strlen(msgS), MPI_CHAR, 0, tag, MPI_COMM_WORLD, MPI_STATUSES_IGNORE);
outfile << msgR << endl;
tag++;
read = true;
}
else if (rank == 2 && !read) {
MPI_Recv(msgR, strlen(msgS), MPI_CHAR, 0, tag, MPI_COMM_WORLD, MPI_STATUSES_IGNORE);
outfile << msgR << endl;
tag++;
read = true;
}
else if (rank == 3 && !read) {
MPI_Recv(msgR, strlen(msgS), MPI_CHAR, 0, tag, MPI_COMM_WORLD, MPI_STATUSES_IGNORE);
outfile << msgR << endl;
tag++;
read = true;
}
else {
cout << "Error!!!";
exit(0);
}
MPI_Finalize();
system("PAUSE");
return 0;
}
有問題。代碼停在MPI_Send例程處,我不知道爲什麼!只需要將一個讀取行從文件發送到任何進程,並將接收到的數據存儲到另一個文件中。如何調試非工作MPI發送?
'randomize' returns大於3的數字,所以你最終得到一個沒有匹配'Recv'的'Send'(這是因爲你使用的是發送和接收的阻塞版本) – niceman
關於每個等級的if語句對你來說合法嗎? –
對不起,我錯了,讓我想想吧 – niceman