我用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 通信始终要求您在所有等级上调用相应的 MPI 函数。 在这种情况下,MPI_Bcast
是正确的函数,但您需要在所有等级上调用它。 查看 https://www.mpich.org/static/docs/v3.1/www3/MPI_Bcast.html 的文档,您将看到 MPI_Bcast 的 "root" 参数确定将值从哪个等级复制到所有其他等级。
正确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 %in", 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 %in", rank, my_data);
}
MPI_Barrier(MPI_COMM_WORLD);
}
return 0;
}