MPI系列主要功能

Ale*_*win 12 c mpi

这是一个非常基本的MPI问题,但我无法解决它.我有一个main函数调用另一个使用MPI的函数.我希望main函数以串行方式执行,而另一个函数并行执行.我的代码是这样的:

int main (int argc, char *argv[])
{
    //some serial code goes here
    parallel_function(arg1, arg2);
    //some more serial code goes here
}

void parallel_function(int arg1, int arg2)
{
    //init MPI and do some stuff in parallel
    MPI_Init(NULL, NULL);
    MPI_Comm_size(MPI_COMM_WORLD, &p);
    MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
    //now do some parallel stuff
    //....
    //finalize to end MPI??
    MPI_Finalize();
}
Run Code Online (Sandbox Code Playgroud)

我的代码运行正常并获得预期的输出,但问题是主函数也在不同的进程中运行,因此串行代码执行不止一次.我不知道它是如何多次运行的,因为我还没有调用MPI_Init(如果在调用parallel_function之前我在main中打印,我会看到多个printf)

我完成后如何让我的程序并行运行?

谢谢你的回复!

sus*_*att 10

看看这个答案.

简单地说:MPI_InitMPI_Finalize不标记并行处理的开始和结束.MPI流程完全并行运行.


Chr*_*ris 9

@suszterpatt指出"MPI进程完全并行运行"是正确的.例如,当您使用并行程序运行时,mpirun或者mpiexec这会启动您请求的进程数(带有-n标志),并且每个进程在开始时开始执行main.所以在你的示例代码中

int main (int argc, char *argv[])
{
    //some serial code goes here
    parallel_function(arg1, arg2);
    //some more serial code goes here
}
Run Code Online (Sandbox Code Playgroud)

每个进程都将执行//some serial code goes here//some more serial code goes here部分(当然它们都会调用parallel_function).parallel_function一旦调用,就没有一个主进程调用然后生成其他进程MPI_Init.

通常最好避免做你正在做的事情:MPI_Init应该是程序中的第一个函数调用之一(理想情况下它应该是第一个).特别注意以下内容(从这里开始):

MPI标准没有说明程序在MPI_INIT之前或MPI_FINALIZE之后可以执行的操作.在MPICH实现中,您应该尽可能少地执行.特别是,避免任何改变程序外部状态的事情,例如打开文件,读取标准输入或写入标准输出.

不尊重这可能导致一些讨厌的错误.

最好将代码重写为以下内容:

int main (int argc, char *argv[])
{

    // Initialise MPI
    MPI_Init(NULL, NULL);
    MPI_Comm_size(MPI_COMM_WORLD, &p);
    MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);

    // Serial part: executed only by process with rank 0
    if (my_rank==0)
    {
        // Some serial code goes here
    }

    // Parallel part: executed by all processes.

    // Serial part: executed only by process with rank 0
    if (my_rank==0)
    {
        // Some more serial code goes here
    }

    // Finalize MPI
    MPI_Finalize();

    return 0;

}
Run Code Online (Sandbox Code Playgroud)

注意:我不是C程序员,所以请小心使用上面的代码.此外,不应该main总是返回一些东西,特别是当定义为int main()