并行数字1到1000的总和

时间:2018-05-21 10:14:40

标签: c++ parallel-processing mpi

以下代码使用2n个CPU来计算11000的总和。每个处理器计算该聚合的一部分并独立显示输出。

计算所有处理器的最终结果由第一个处理器收集并聚合,最终结果显示在输出中。

#include <iostream>
#include <stdio.h>
#include <mpi.h>

static int MyNode, Nodes;
using namespace std;
int main(int* argc, char** argv[])
{
    MPI_Init(argc, argv);
    MyNode = MPI_Comm_rank(MPI_COMM_WORLD, &MyNode);
    Nodes =  MPI_Comm_size(MPI_COMM_WORLD, &Nodes);
    MPI_Status status;
    int sum = 0;
    int accum = 0;
    int FIndex = 1000 * MyNode / Nodes + 1;
    int LIndex = 1000 * (MyNode + 1) /
        Nodes;
    for (int I = FIndex; I <= LIndex; I = I + 1)
        sum += I;
    if (MyNode != 0)
        MPI_Send(&sum, 1, MPI_INT, 0, 1,
            MPI_COMM_WORLD);
    else
        for (int J = 1; J < Nodes; J = J + 1) {
            MPI_Recv(&accum, 1, MPI_INT,
                J, 1, MPI_COMM_WORLD,
                &status);
            sum += accum;
        }
    if (MyNode == 0) {
        cout << "Total Nodes is " << Nodes << ".The sum from 1 to 1000 is: " << sum << endl;
    }
    MPI_Finalize();
    return 0;
}

运行后,遇到问题:Integer division by zero.(MyNode / Nodes)

为什么MyNodeNodes为零?

2 个答案:

答案 0 :(得分:1)

以下函数返回错误(如果有)

MyNode = MPI_Comm_rank(MPI_COMM_WORLD, &MyNode);
Nodes =  MPI_Comm_size(MPI_COMM_WORLD, &Nodes);

由于您将错误状态存储在MyNode和Nodes中,(在这种情况下没有错误)MyNOde和Nodes的值为0.

将其更改为此

int err;
err = MPI_Comm_rank(MPI_COMM_WORLD, &MyNode);
err =  MPI_Comm_size(MPI_COMM_WORLD, &Nodes);

答案 1 :(得分:1)

只需将参考传递给MyNodeNodes

MPI_Comm_rank(MPI_COMM_WORLD, &MyNode);
MPI_Comm_size(MPI_COMM_WORLD, &Nodes);
  

MPI_Comm_size成功返回MPI_SUCCESS。否则,返回   value是错误代码。