【问题标题】:MPI pass value to all the coresMPI 将值传递给所有内核
【发布时间】:2019-07-27 20:26:07
【问题描述】:

我使用 C 编写 MPI 程序。假设我使用 10 个内核。我想将glob 传递给所有其他内核,但以下代码中的glob 由其中一个内核执行,这是非法的,代码将失效。

for ( i = 0; i < n_loc; i++ ) {   /*n_loc is the local number based on each core*/
    if ( a_loc[i] == glob ) {  /*a_loc is a local array based on each core*/
        glob += 1;
        MPI_Bcast ( &glob, 1, MPI_INT, MYID, MPI_COMM_WORLD );
    }
}

那么我该怎么做才能解决这个问题,全局变量被 10 个核心之一更改但我想通知其他 9 个核心?

【问题讨论】:

  • 在 MPI 中不存在单方面的集体。我不知道您要实现什么目标,但您的程序似乎有一个未定义的并行行为。请发布minimal reproducible example,以便您了解如何最好地前进。

标签: c mpi broadcast


【解决方案1】:

请记住,MPI 通信始终要求您在所有队伍中调用适当的 MPI 函数。 MPI_Bcast 是在这种情况下使用的正确函数,但您需要在所有级别上调用它​​。检查https://www.mpich.org/static/docs/v3.1/www3/MPI_Bcast.html 的文档,您会看到 MPI_Bcast 的“根”参数决定了该值从哪个等级复制到所有其他等级。

正确使用 MPI_Bcast 的示例:

#include "stdio.h"
#include "mpi.h"

int main(){
    MPI_Init(NULL, NULL);
    int comm_size;
    MPI_Comm_size(MPI_COMM_WORLD, &comm_size);
    int rank; // Get the number of the rank
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);  

    int my_data = rank; // Set mydata = rank -- will be different on all ranks
    for(int i=0; i < comm_size; i++){
        if(rank == i){
            printf("Rank %i: Value %i\n", rank, my_data);
        }
        MPI_Barrier(MPI_COMM_WORLD);
    }

    // Communicate the value of my_data from rank 0 to all other ranks
    int root_rank = 0;
    if(rank == root_rank){
        printf("Broadcasting from rank %i:\n", root_rank);
    }
    MPI_Bcast(&my_data, 1, MPI_INT, root_rank, MPI_COMM_WORLD);

    // my_data is now 0 on all ranks
    for(int i=0; i < comm_size; i++){
        if(rank == i){
            printf("Rank %i: Value %i\n", rank, my_data);
        }
        MPI_Barrier(MPI_COMM_WORLD);
    }
    return 0;
}

【讨论】:

    猜你喜欢
    • 2011-08-08
    • 2016-04-14
    • 2011-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多