首页 > 解决方案 > 在 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;
}




标签: mpi

解决方案


推荐阅读