#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
//Please run this program with 4 processes
int main(int argc, char* argv[])
{
MPI_Init(&argc, &argv);
// Check that 4 MPI processes are used
int comm_size;
MPI_Comm_size(MPI_COMM_WORLD, &comm_size);
if (comm_size != 4)
{
printf("This application is meant to be run with 4 MPI processes, not %d.\n", comm_size);
MPI_Abort(MPI_COMM_WORLD, EXIT_FAILURE);
}
// Get my rank in the global communicator
int my_rank;
MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
// Determine the colour and key based on whether my rank is even.
int colour;
int key;
if (my_rank % 2 == 0)
{
colour = 0;
key = my_rank;
}
else
{
colour = 1;
key = comm_size - my_rank;
}
// Split the global communicator
MPI_Comm new_comm;
MPI_Comm_split(MPI_COMM_WORLD, colour, key, &new_comm);
// Get my rank in the new communicator
int my_new_comm_rank;
MPI_Comm_rank(new_comm, &my_new_comm_rank);
// Print my new rank and new communicator
printf("I am process %d and I belong to %x\n", my_rank,new_comm);
MPI_Finalize();
return EXIT_SUCCESS;
}
上面的代码假设将4个进程分成2个不同的subcommunicator,进程0和2在一个,进程1和3在另一个。然而这个程序的输出是:
I am process 3 and I belong to 84000000
I am process 1 and I belong to 84000000
I am process 2 and I belong to 84000000
I am process 0 and I belong to 84000000
没有任何意义的是它们都属于同一个subcommunicator(84000000)。似乎无法将它们分成不同的子通信器。 顺便说一句,我在带有 MSMPI 的 Windows 操作系统中运行它。
您正在以共享内存的方式思考。 MPI 使用分布式内存:每个进程都有自己的地址空间。因此,一个进程上的地址
84000000
与另一个进程上的相同地址是完全不同的对象。他们有相同的地址纯属巧合。
所以你可能会想,我如何测试这些子通信器是否确实相同?答案是:你不能。如果两个进程在不同的通信器中,它们甚至看不到另一个。想一想:您如何处理您不在其中的通信器?