parallel code in sub functions
-
28 ตุลาคม 2554 14:24
Hi everyone,
I'm currently coding with MPI. The only parallelism I want to do is in a subfunction called by the main one. I explicitly declare MPI starts and end in the sub function. While I found, when the program is excuted, parallelism also exists in the main function. This is not what I want. Can anyone help me?
The following is an example:
#include <stdio.h>
#include <mpi.h>
int argc;
char **argv;
int subfunction();
int main()
{
subfunction(); // call parallel sub function
printf("sub function is called\n");
}
int subfunction()
{
int numprocs;
int myrank;
MPI_Init(&argc, &argv); // start parallelism
MPI_Comm_size(MPI_COMM_WORLD, &numprocs);
MPI_Comm_rank(MPI_COMM_WORLD, &myrank);
printf("Hello, world! I'm process %d\n",myrank);
MPI_Finalize(); //end parallelism
return(0);
}The output of the code is:
mpirun -np 2 excute
Hello, world! I'm process 0
Hello, world! I'm process 1
sub function is called
sub function is called
- แก้ไขโดย adot120 28 ตุลาคม 2554 14:27
ตอบทั้งหมด
-
1 พฤศจิกายน 2554 23:56
Hello,
When you execute the app with mpiexec -n [numprocesses] myApp, it will invoke [numprocesses] for myApp. So even you don't have subfunction() in your program, still it will have the same output.
One way to work around your question is to using just one rank for the functions which you don't want to run with multiple processes. For example
#include <stdio.h> #include <mpi.h> int argc; char **argv; int subfunction(); int main() { int numprocs; int myrank; MPI_Init(&argc, &argv); // start parallelism MPI_Comm_size(MPI_COMM_WORLD, &numprocs); MPI_Comm_rank(MPI_COMM_WORLD, &myrank); subfunction(); // call parallel sub function // Only rank 0 execute this chunk of code if (myrank == 0) printf("sub function is called\n"); } int subfunction() { printf("Hello, world! I'm process %d\n",myrank); MPI_Finalize(); //end parallelism return(0); }
Give it a try and let me know whether this works for you.Thanks,
James