I like to implement an MPI program using broadcasting method. I find out some code block for broadcasting method from text book and try to modify my this code.
#include <stdio.h>
#include <math.h>
#include<mpi.h>
double sum(int n);
int main(void){
double local_sum, total_sum;
int source;
int local_n;
MPI_Init(NULL,NULL);
MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
MPI_Comm_size(MPI_COMM_WORLD, &comm_sz);
void Get_input(int my_rank, int comm_sz, int *n){
if(my_rank==0){
printf("Enter the value for n:");
scanf("%d",n);
}
MPI_Bcast(n,1,MPI_INT,0,MPI_COMM_WORLD);
}
local_n= n/comm_sz;
local_sum=sum(local_n);
if ( my_rank != 0) {
MPI_Send (&local_sum , 1, MPI_DOUBLE , 0, 0, MPI_COMM_WORLD ) ;
}
else{
total_sum = local_sum;
for(source=1;source<comm_sz;source ){
MPI_Recv (&local_sum , 1, MPI_DOUBLE , source , 0, MPI_COMM_WORLD , MPI_STATUS_IGNORE ) ;
total_sum =local_sum;
}
}
if(my_rank==0){
printf("Sum is=%lf",total_sum);
printf("\n");
}
MPI_Finalize();
return 0;
}
double sum(int n){
int i;
double cal_sum=0;
for (i =0;i <= n;i ) {
cal_sum = cal_sum 4*(pow (-1, i))/((2*i) 1);
}
return cal_sum;
}
Now I got error like this:
mpi_sumB.c: In function ‘main’:
mpi_sumB.c:13:34: error: ‘my_rank’ undeclared (first use in this function)
MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
^
mpi_sumB.c:13:34: note: each undeclared identifier is reported only once for each function it appears in
mpi_sumB.c:14:35: error: ‘comm_sz’ undeclared (first use in this function)
MPI_Comm_size(MPI_COMM_WORLD, &comm_sz);
^
mpi_sumB.c:25:12: error: ‘n’ undeclared (first use in this function)
local_n= n/comm_sz;
Now it is obvious I got this errors because I know where I write down the void Get_input(int my_rank, int comm_sz, int *n)
may be this is not the right place for this function. But I did not get any clear guidance where I need to define this function.
Thank you for any help
Edit: I am not looking for C programming syntax or nested function. This is an mpi program implementing in c, more specifically broadcasting problem. I would like to know generally in mpi program where we need to define broadcasting.
CodePudding user response:
I would like to know generally in mpi program where we need to define broadcasting.
The context of the application matters. If you need to broadcast, say configuration information (for example, like in your case, the input size), you need to do the broadcast once your lead rank (say rank 0
) has the corresponding information. So, you can call MPI_Bcast
immediately after that.
If you are asking about the place to define the function i.e before the main or after the main. It doesn't matter. The order of functions inside a file is arbitrary. It does not matter if you put function one at the top of the file and function two at the bottom, or vice versa. Caveat: In order for one function to "see" (use) another function, the "prototype" of the function must be seen in the file before the usage. See this.