我工作的这个MPI代码,一切都差不多,它应该工作,但我有麻烦的程序的输出写入文件。 下面是一些代码来说明我的问题
int main(int argc, char *argv[]){
FILE *filename;
int size, my_rank;
int count =0;
int tag =99;
int limit = 5;
MPI_Init(&argc, &argv);
MPI_Status status;
MPI_Comm_size(MPI_COMM_WORLD,&size);
MPI_Comm_rank(MPI_COMM_WORLD,&my_rank);
if(my_rank ==0)
printf("Process %d started the game and initialized the counter\n\n",my_rank);
MPI_Barrier(MPI_COMM_WORLD);
if (size != 2) {//abort if the number of processes is not 2.
fprintf(stderr, "only 2 processes shall be used for %s\n", argv[0]);
MPI_Abort(MPI_COMM_WORLD, 1);
}
int peer_rank = (my_rank + 1) % 2;
while(count < limit){
filename = fopen("ping_pong_output.txt", "w");
if(my_rank == count % 2){
count++;
MPI_Send(&count, 1, MPI_INT, peer_rank, tag, MPI_COMM_WORLD);
printf("Process %d incremented the count (%d) and sent it to process %d\n\n", my_rank, count, peer_rank);
MPI_Barrier(MPI_COMM_WORLD);
fprintf(filename,"Process %d incremented the count (%d) and sent it to process %d\n", my_rank, count, peer_rank);
} else{
MPI_Barrier(MPI_COMM_WORLD);
MPI_Recv(&count, 1, MPI_INT, peer_rank, tag, MPI_COMM_WORLD,
&status);
MPI_Barrier(MPI_COMM_WORLD);
printf("Process %d received the count from process %d.\n", my_rank, peer_rank);
fprintf(filename,"Process %d received the count.\n", peer_rank);
}
fclose(filename);
}
MPI_Finalize();
return 0;}
我想写到一个文件中的printf语句的输出,但是代码只输出在最后while循环迭代文件的最后的printf。 如果有人有一个解决这个问题,将不胜感激。