I'm learning MPI and was fiddling with some of the besic functions, like MPI_Bcast. Usually one has the message in the main rank (i.e. 0) and broadcasts it to the others, so something like (this is a basic example from my notes)
#include "mpi.h"
#include <iostream>
int main(int argc, char* argv[]){
// common buffer 'n' for every process
int n, myid, numprocs, i;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &numprocs);
MPI_Comm_rank(MPI_COMM_WORLD, &myid);
// at first only process 0 has the value of n, e.g. n=5
if(myid==0){
printf("Enter n: ");
scanf("%d", &n);
}
// broadcasted to every other process, now each of
// has a separate n that can be independently modified
MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD);
if(myid==0){
++n; // 5->6 for proc 0
}
if(myid==1){
n+=2; // 5->7 for proc 1
}
printf("n from process %d is %d\n", myid, n);
/*
upon execution (-np 4):
Enter n: 5
n from process 0 is 6
n from process 1 is 7
n from process 2 is 5
n from process 3 is 5
*/
return 0;
}
Out of curiosity i tried to put the scanf out of the if clause, so to give every process an initial value for n:
#include "mpi.h"
#include <iostream>
int main(int argc, char* argv[]){
int n, myid, numprocs, i;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &numprocs);
MPI_Comm_rank(MPI_COMM_WORLD, &myid);
printf("Enter n: ");
scanf("%d", &n);
MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD);
if(myid==0){
++n;
}
if(myid==1){
n+=2;
}
printf("n from process %d is %d\n", myid, n);
return 0;
}
When executing the code this is the result (-np 3):
Enter n: Enter n: Enter n: 5
n from process 0 is 6
Every process execute the scanf function but it seems that only the 0 prints the results. I wanted to ask why it happens, although i can figure that this is a misuse of the parallel input.