none
parallel code in sub functions RRS feed

  • Question

  • 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

     

     


    • Edited by adot120 Friday, October 28, 2011 2:27 PM
    Friday, October 28, 2011 2:24 PM

All replies

  • 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

    Tuesday, November 1, 2011 11:56 PM