【发布时间】:2021-04-11 14:04:01
【问题描述】:
假设进程 0 有一个整数数组,我们应该计算所有的阶乘 数组中的元素。修改程序以便将数组发送到计算所有的进程 1 阶乘并将结果返回到进程 0。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <mpi.h>
int main (int argc, char ** argv)
{
int rank, size,code,tag=100;
int a[10]={1,2,3,4,5,6,7,8,9,10};
int count,fact = 1,i,j,k;
MPI_Init (&argc, &argv); /* starts MPI */
MPI_Comm_rank (MPI_COMM_WORLD, &rank); /* get current process id */
if (rank == 0) {
for ( i = 0; i < 9; ++i)
{
code=MPI_Send(&a[i],1, MPI_INTEGER,1,tag, MPI_COMM_WORLD);
code=MPI_Recv(&fact,1, MPI_INTEGER,1,tag, MPI_COMM_WORLD,MPI_STATUSES_IGNORE);
printf("Process %d,Result=%d\n",rank,fact);
}
}
else if (rank == 1)
{
for (int j = 0; j < 9; ++j)
{
code=MPI_Recv(&a[j],1, MPI_INTEGER,0,tag, MPI_COMM_WORLD,MPI_STATUSES_IGNORE);
count = j;
for ( k = 0; k < count; ++k)
{
fact = fact*(j+1);
code=MPI_Send(&fact,1, MPI_INTEGER,0,tag, MPI_COMM_WORLD);
}
}
}
MPI_Comm_size (MPI_COMM_WORLD, &size); /* get number of processes */
MPI_Finalize();
return 0;
}
【问题讨论】:
标签: arrays c parallel-processing mpi factorial