我正在查看其他人的 MPI 代码,并且有很多次main()
在其他函数中声明和使用变量(某些 MPI 特定)。我是 MPI 的新手,但在我的编程经验中,通常不应该这样做。基本上我很难确定这样做是否安全(不会引发错误)。
整个代码很长,所以我将在下面给出一个简化版本:
int main(int argc, char** argv) {
// ...unrelated code
int num_procs, local_rank, name_len;
MPI_Comm comm_new;
MPI_Init(&argc, &argv);
MPI_Get_processor_name(proc_name, &name_len);
create_ring_topology(&comm_new, &local_rank, &num_procs);
// ...unrelated code
MPI_Comm_free(&comm_new);
MPI_Finalize();
}
void create_ring_topology(MPI_Comm* comm_new, int* local_rank, int* num_procs) {
MPI_Comm_size(MPI_COMM_WORLD, num_procs);
int dims[1], periods[1];
int dimension = 1;
dims[0] = *num_procs;
periods[0] = 1;
int* local_coords = malloc(sizeof(int)*dimension);
MPI_Cart_create(MPI_COMM_WORLD, dimension, dims, periods, 0, comm_new);
MPI_Comm_rank(*comm_new, local_rank);
MPI_Comm_size(*comm_new, num_procs);
MPI_Cart_coords(*comm_new, *local_rank, dimension, local_coords);
sprintf(s_local_coords, "[%d]", local_coords[0]);
}