dang92
dang92

Reputation: 41

c++MPI instruction before all process started

assuming i have code like this:

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

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?

Upvotes: 2

Views: 1063

Answers (2)

Hristo Iliev
Hristo Iliev

Reputation: 74395

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().

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();
}

(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)

Then run it like:

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

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

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

Upvotes: 1

Gilles Gouaillardet
Gilles Gouaillardet

Reputation: 8395

There is no portable way to achieve that !

Also, note that most MPI implementations start all the MPI tasks at the same time via mpirun. Long story short, MPI_Init() makes independent processes become a MPI task from a unique job.

with recent Open MPI, you can try to test the PMIX_RANK environment variable, and i can only guess MPICH derivatives have a similar way to do the trick.

but once again, these are just non portable tricks, and you should not be doing that.

Upvotes: 1

Related Questions