c++ - 这个 C++ 程序中的 MPI_Bcast() 是做什么用的?

标签 c++ multiprocessing mpi

我开始学习 MPI 并从 Russian IT blog Habrahabr 中获取了本教程代码示例:

#include <mpi.h>
#include <iostream>
#include <windows.h>
using namespace std;

double Fact(int n)
{ 
    if (n==0) return 1;
    else return n*Fact(n-1);
}

int main(int argc, char *argv[])
{
    int n;
    int myid;
    int numprocs;
    int i;
    int rc;

    long double drob,drobSum=0,Result, sum;
    double startwtime = 0.0;
    double endwtime;

    n = atoi(argv[1]);

    if (rc= MPI_Init(&argc, &argv)) { 
        cout << "Launch error" << endl;
        MPI_Abort(MPI_COMM_WORLD, rc);
    } 

    MPI_Comm_size(MPI_COMM_WORLD,&numprocs); 
    MPI_Comm_rank(MPI_COMM_WORLD,&myid); 

    if (myid == 0) {
        startwtime = MPI_Wtime();
    }

    MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD);

    for (i = myid; i <= n; i += numprocs)
    { 
        drob = 1/Fact(i);
        drobSum += drob;
    }

    MPI_Reduce(&drobSum, &Result, 1, MPI_LONG_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);

    cout.precision(20);

    if (myid == 0)
    {   
        cout << Result << endl; 
        endwtime = MPI_Wtime();
        cout << (endwtime-startwtime)*1000 << endl;      
    }

    MPI_Finalize();
    return 0;
}

我的问题是他们为什么需要那个

MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD);

在那里,如果在所有进程中都设置了 n

n = atoi(argv[1]);

无论如何。

这只是一个错误还是有任何目的?我测试了代码,没有它也能正常工作。

我想也许广播意味着一些过程工作流障碍,用于正确计算时间测量或其他东西。

我还认为它可能存在,因为 n 初始化在 MPI_Init() 调用之前进行。 如果我将 n = atoi(argv[1]); 放在 MPI_Init() 之后,我是否需要在此代码中使用 MPI_Bcast()

最佳答案

MPI_Init() 之前的任何内容都是 undefined behavior in MPI .如果您不想广播命令行参数,那么您应该在 MPI_Init(&argc, &argv) 之后使用 argvargc,因为这样它们就会保证可用于所有任务。

代码工作正常,因为许多 MPI 实现在初始化之前使 argvargc 可用,但您不应依赖此行为。

关于c++ - 这个 C++ 程序中的 MPI_Bcast() 是做什么用的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55996790/

相关文章:

c++ - 如何避免类名和方法名重名?

c++ - Qt:重叠半透明QgraphicsItem

python - 如何沟通两个独立的python进程?

c++ - 在 map C++ 中使用列表

c++ - 是否可以实现自动全局转换?

python - 具有不同功能的多进程池

python - 在 Python 中并行运行函数

c - MPI 使用 MPI_Send 和 MPI_Reduce 发送消息

c++ - MPI 收集不同尺寸

eclipse - java.io.FileNotFoundException : null\conf\wrapper. conf(系统找不到指定的路径)