1

首先,我在互联网上搜索过,但找不到答案。也许原因是我是 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 才读完?但这不起作用。

4

1 回答 1

0

其他进程看不到更新的值,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;  

}
于 2013-01-11T15:23:32.770 回答