Burak Keceli
Burak Keceli

Reputation: 953

MPI: How to make other processors to wait master processors until its job is finished

First of all, I have searched the Internet but could not find the answer. Maybe the reason is I am newbie on MPI. Here is the question:

Firstly I want master processor to read a txt file. Then take the enough info. But during this I want others to wait reading process.

here is my code:

int processorID;  
int numberOfProcessors;  


int main(int argc, char* argv[]){
MPI_Init(&argc, &argv);  
MPI_Comm_size(MPI_COMM_WORLD ,&numberOfProcessors);  
MPI_Comm_rank(MPI_COMM_WORLD ,&processorID);

int a, b, c;

if(MASTER){
    FILE *myFile;           
    myFile=fopen("input.txt", "r");

    fscanf(myFile, "%d", &a);
    fscanf(myFile, "%d", &b);
    fscanf(myFile, "%d", &c);

}
    MPI_Barrier(MPI_COMM_WORLD);

    if(SLAVE){
            printf("%d\n" ,a);
            printf("%d\n" ,processorID);
    }
MPI_Finalize();  
return 0;  

}

Should not I use MPI_Barrier? For example I have 5 processors, and the 0 is master. Thanks to MPI_Barrier, other 1-2-3-4 do not have to wait 0 until it finishes reading? but this is not working.

Upvotes: 1

Views: 6159

Answers (1)

hmatar
hmatar

Reputation: 2419

Other processes can not see the updated value of a because it is process local. Send it to others using MPI_Bcast. This way all processes wait at MPI_Bcast.

I modified your code as follows;

int processorID;  
int numberOfProcessors;  


int main(int argc, char* argv[]){
MPI_Init(&argc, &argv);  
MPI_Comm_size(MPI_COMM_WORLD ,&numberOfProcessors);  
MPI_Comm_rank(MPI_COMM_WORLD ,&processorID);

int a, b, c;

if(!processorID){ // master
    FILE *myFile;           
    myFile=fopen("input.txt", "r");

    fscanf(myFile, "%d", &a);
    fscanf(myFile, "%d", &b);
    fscanf(myFile, "%d", &c);
    MPI_Bcast(&a, 1, MPI_INT, 0, MPI_COMM_WORLD);

}
    //MPI_Barrier(MPI_COMM_WORLD);
else {
    //if(SLAVE){
            // blocks at Bcast waiting for a. Prints value read by MASTER
            MPI_Bcast(&a, 1, MPI_INT, 0, MPI_COMM_WORLD); 
            printf("%d\n" ,a);
            printf("%d\n" ,processorID);
    }
MPI_Finalize();  
return 0;  

}

Upvotes: 0

Related Questions