#include "mpi.h"
#include <stdio.h>
int main(int argc,char *argv[]){
int numtasks, rank, rc, count, tag=1, i =0;
MPI_Status Stat;
MPI_Init(&argc,&argv);
MPI_Comm_size(MPI_COMM_WORLD, &numtasks);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
if (rank == 0) //for process 0 we print received messages
{
for(i=0; i< 9; i ++){
printf("value of i is: %d\n",i );
rc = MPI_Recv(&inmsg, 1, MPI_CHAR, MPI_ANY_SOURCE, tag, MPI_COMM_WORLD, &Stat);
printf("Task %d: Received %d char(s) from task %d with tag %d \n", rank, count, Stat.MPI_SOURCE, Stat.MPI_TAG);
}
}
else //for the other 9 processes
{
if(rank % 2 == 0){ //if rank is an even number
rc = MPI_Send(&outmsg, 1, MPI_CHAR, 0, tag, MPI_COMM_WORLD); //send message to process with rank 0
}
}
MPI_Finalize();
}
//
此程序运行10个进程。等级为0的进程接收消息,如果源进程的编号为偶数,则将其打印出来。等级为0以外的进程向等级为0的进程发送包含字符'x'的消息
现在,关于等级0,它具有一个for循环,该循环基本上循环9次。在循环中,它打印出迭代变量i的值以及接收到的字符和源进程。
但是,当我运行程序时,它不会终止。
输出看起来像这样:
Task 0: Received 0 char(s) from task 2 with tag 1
value of i is: 1
Task 0: Received 0 char(s) from task 6 with tag 1
value of i is: 2
Task 0: Received 0 char(s) from task 4 with tag 1
value of i is: 3
Task 0: Received 0 char(s) from task 8 with tag 1
value of i is: 4
如何获取它来打印i
的其他值,例如5,6,7,8,9?
答案 0 :(得分:2)
您正在使用主从结构进行并行处理,您的进程0是主进程,正在等待其他9个进程的输入,但是在您的代码中,只有具有偶数ID的进程才会触发输出,即进程2、4、6、8。
您没有为进程1、3、5、7和9设置行为,因此主服务器仍在等待它们,因此程序在等待并行进程完成:
您需要在此处完成源代码
if(rank % 2 == 0){ //if rank is an even number
rc = MPI_Send(&outmsg, 1, MPI_CHAR, 0, tag, MPI_COMM_WORLD); //send message to process with rank 0
}else{
//logic for process 1,3,5,7,9
}