【问题标题】:MPI: How to make other processors to wait master processors until its job is finishedMPI:如何让其他处理器等待主处理器直到其工作完成
【发布时间】:2012-12-26 04:54:06
【问题描述】:

首先,我搜索了互联网但没有找到答案。也许原因是我是 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_Barrier 吗?例如我有5个处理器,0是master。感谢 MPI_Barrier,其他 1-2-3-4 不必等到 0 才读完?但这不起作用。

【问题讨论】:

    标签: c mpi


    【解决方案1】:

    其他进程看不到a的更新值,因为它是本地进程。使用MPI_Bcast 将其发送给其他人。这样所有进程都在 MPI_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_Barrier。实际上我无法确切理解屏障的作用。
    猜你喜欢
    • 2012-05-05
    • 1970-01-01
    • 2020-04-28
    • 2020-09-21
    • 1970-01-01
    • 1970-01-01
    • 2012-12-26
    • 2018-10-03
    • 1970-01-01
    相关资源
    最近更新 更多