所有进程启动前的c

所有进程启动前的c

本文介绍了所有进程启动前的c++MPI指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这样的代码:

    int main(..){
            cout<<"something"<<endl;
            MPI_INIT(...);
            ..
            ..
            ..
            MPI_FINALIZE();
    }

我认为 init 之前的 cout 只会被主进程执行一次.相反,它执行的次数与进程数一样多.如何只运行一次指令,然后在所有进程启动之前?

I thought the cout before the init would be executed only once by the main process. Instead, it s executed as many times as the number of process. How can i run an instruction only one time and before that all process are started?

推荐答案

您将 MPI 误认为 OpenMP.后者使用 fork-join 模型,其中程序最初作为串行代码运行,并产生线程以并行执行某些区域.MPI 是一种多进程范式,通常所有进程一起启动并在 MPI_Init() 之前执行完全相同的代码.

You are mistaking MPI for OpenMP. The latter uses the fork-join model where the program runs as a serial code initially and spawns threads to perform certain regions in parallel. MPI is a multi-process paradigm and typically all processes are started together and execute exactly the same code before MPI_Init().

一个相对可移植的解决方案是将许多 MPI 实现执行 MPMD(多程序多数据)启动的能力与导致执行特定预初始化代码的命令行参数相结合:

A relatively portable solution is to combine the ability of many MPI implementations to perform MPMD (multiple program multiple data) launches with a command line argument that results in that particular pre-initialisation code being executed:

int main (int argc, char **argv) {
   if (argc > 1 && argv[1] == "-preinit") {
      ...
      cout << "Something" << endl;
   }
   MPI_Init(NULL, NULL);
   ..
   ..
   MPI_Finalize();
}

(argv[1] == "-preinit" 是伪代码;您应该使用字符串比较函数,例如 strncmp 或解析命令行参数,例如 getopt)

(the argv[1] == "-preinit" is pseudo-code; you should use a string comparison function such as strncmp or a library that parses the command-line arguments such as getopt)

然后像这样运行:

mpiexec -n 1 ./program -preinit : -n 99 ./program

这将启动 100 个 MPI 进程,其中只有一个接收 -preinit 命令行参数.

This will launch 100 MPI processes with only one of them receiving the -preinit command-line argument.

不过,真正可移植的方法是先初始化 MPI,然后获取等级,然后在等级 0 中做任何必须做的事情.

Still, the truly portable way is to first initialise MPI, then obtain the rank, and do whatever has to be done in rank 0.

这篇关于所有进程启动前的c++MPI指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 00:38