mpi - 在 MPI 中使用 MPI_BCAST 和 MPI_Reduce 对数字求和
问题描述
我正在将名为 number.txt 的 txt 文件中的数字读取到数组 num[64] 中。进程 0 应该读取 txt 文件并向所有进程广播 num[]。然后我必须使用 reduce 操作来计算所有部分和的总和,并且过程 0 最终应该打印总和。我无法使用进程 0 打印最终值(在变量“total”中)。我在最后使用了 if 循环,但没有打印。部分总和打印正确且正确。如何使用进程 0 打印总计?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <mpi.h>
int main(int argc, char** argv){
int size, rank,i,j,count=0;
int sum=0,total=0;
int num[64];
MPI_Init(&argc,&argv);
MPI_Comm_size(MPI_COMM_WORLD,&size);
MPI_Comm_rank(MPI_COMM_WORLD,&rank);
if(rank==0)
{
//Read File:
FILE *fp;
fp = fopen("number.txt" , "r");
if(fp == NULL)
{
perror("Error opening file");
return(-1);
}
while (!feof (fp))
{
fscanf (fp, "%d", &i);
num[count]=i;
count+=1;
}
fclose (fp);
}
MPI_Bcast(num, 64, MPI_INT, 0, MPI_COMM_WORLD);
for(i=(rank*16);i<((rank*16)+16);i++)
{
sum+=num[i];
}
printf("sum_%d: %d\n",rank,sum);
MPI_Reduce(&sum,&total,4,MPI_INT,MPI_SUM,0,MPI_COMM_WORLD);
if(rank==0)
{
printf("final total: %d\n",total);
}
MPI_Finalize();
return 0;
}
解决方案
推荐阅读
- kotlin - 来自 2 个现有数组的 kotlin distinct() 或 distinctBy {}
- python-3.x - 为什么 (ModuleNotFoundError: No module named 'scapy') 出现?
- ubuntu - NGINX 多个反向代理
- java - 在具有两个数据集(训练和测试集)的神经网络上需要帮助
- javascript - 返回一个 16 位 UUID,其中在第 7、11、15 和第 19 位我需要添加一个 hiphen
- hash - 两个 SHA-256 哈希的异或
- java - http.antMatcher("/**") .authorizeRequests().antMatchers("/") 中的antMatcher("/**") 需要什么?
- c# - 使用反射在 C# Net Core 中查找不是其他类的类成员
- javascript - 从表中的多个选定行中获取 td
- python-3.x - 如何在 django rest 框架中部分更新模型类