我是 MPI 的初学者,我有作业。我不是要求你解决它,我只需要提示我的程序出现故障的原因。
这是问题所在
编写一个模拟乒乓球桌游戏的 MPI C 程序。只能使用 2 个进程。进程使用 MPI_Send 和 MPI_Recv 不断地向彼此退回消息(指定次数)。该消息由一个整数计数变量组成,每个进程在发送之前都会递增该变量。计数变量在开始游戏之前初始化为零。
Output
名为 ping_pong_output.txt 的文本文件形成如下示例: if count = 5
进程 0 开始游戏并初始化计数 进程 0 增加计数 (1) 并将其发送给进程 1
进程收到计数 进程 0 递增计数 (2) 并将其发送回进程 0
进程收到计数 进程 0 递增计数 ( 3 ) 并将其发送回进程 1
进程收到计数 进程 0 递增计数 ( 4 ) 并将其发送回进程 0
进程收到计数 进程 0 递增计数 ( 5 ) 并将其发送回进程 1
请注意以下事项:
- 进程轮流作为发送者和接收者(需要使用%)
- 该程序应该只允许 2 个进程玩游戏
我写的代码
#include <stdlib.h>
#include <stdio.h>
#include <mpi.h>
#include <time.h>
int main(int argc, char * argv[]){
int size=0,my_rank=0,tag=1,count;
MPI_Status status;
MPI_Init(&argc,&argv);
MPI_Comm_size(MPI_COMM_WORLD,&size);
MPI_Comm_rank(MPI_COMM_WORLD,&my_rank);
MPI_Barrier(MPI_COMM_WORLD);
if (my_rank==0){
count=0;
count++;
printf("Process 0 started the game and initialized the count\nProcess 0 incremented the count and sent it to process 1\n");
MPI_Send(&count,1,MPI_INT,1,tag,MPI_COMM_WORLD);
}
MPI_Barrier(MPI_COMM_WORLD);
while (count<=5){
MPI_Barrier(MPI_COMM_WORLD);
MPI_Recv(&count,1,MPI_INT,(my_rank+1)%2,tag,MPI_COMM_WORLD,&status);
printf("Process %d received the count\n",my_rank);
count++;
MPI_Send(&count,1,MPI_INT,(my_rank+1)%2,tag,MPI_COMM_WORLD);
printf("process %d incremented the count (%d) & sent it back to process %d\n",my_rank,count,(my_rank+1)%2);
}
MPI_Finalize();
return 0;
}
我得到的输出是:
进程1收到计数
进程 1 增加计数 (2) 并将其发送回进程 0
进程1收到计数
进程 1 增加计数 (4) 并将其发送回进程 0
进程1收到计数
进程 1 增加计数 (6) 并将其发送回进程 0
进程0开始游戏并初始化计数
进程 0 增加计数并将其发送给进程 1
进程 0 收到计数
进程 0 增加计数 (3) 并将其发送回进程 1
进程 0 收到计数
进程 0 增加计数 (5) 并将其发送回进程 1
进程 0 收到计数
进程 0 增加计数 (7) 并将其发送回进程 1
我不明白为什么进程 1 首先运行,循环甚至在 if 语句之前运行。所有这些 MPI_Barrier 可能都没用,但它们是出于绝望。