C MPI:如何使其他处理器等待主处理器直到其任务完成

C MPI:如何使其他处理器等待主处理器直到其任务完成,c,mpi,C,Mpi,首先,我在网上搜索过,但没有找到答案。也许是因为我是MPI的新手。问题是: 首先,我想让主处理器读取一个txt文件。然后获取足够的信息。但在此期间,我希望其他人等待阅读过程 这是我的密码: int processorID; int numberOfProcessors; int main(int argc, char* argv[]){ MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD ,&numbe

首先,我在网上搜索过,但没有找到答案。也许是因为我是MPI的新手。问题是:

首先,我想让主处理器读取一个txt文件。然后获取足够的信息。但在此期间,我希望其他人等待阅读过程

这是我的密码:

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;  
}


我不应该使用MPI_屏障吗?例如,我有5个处理器,0是主处理器。多亏了MPI_屏障,其他1-2-3-4不必等到0完成读取?但这不起作用。

其他进程无法看到
a
的更新值,因为它是进程本地的。使用
MPI\u Bcast
将其发送给其他人。这样,所有进程都在
MPI\u Bcast
上等待

我修改了你的代码如下

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;  

}

谢谢你,现在我明白了。我想,你是在建议我不要使用MPI_屏障。事实上,我不能确切地理解屏障的作用。