方式1:
每次寻找自己的partner,规定my_rank较小的接收,较大的发送。
int Global_sum(int my_int, int my_rank, int comm_sz, MPI_Comm comm)
{
int partner, recvtemp;
int my_sum = my_int;
unsigned bitmask = 1;
while (bitmask < comm_sz) {
partner = my_rank ^ bitmask;
if (my_rank < partner) {
MPI_Recv(&recvtemp, 1, MPI_INT, partner, 2, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
my_sum += recvtemp;
} else {
MPI_Send(&my_sum, 1, MPI_INT, partner, 2, MPI_COMM_WORLD);
return 0;
}
bitmask *= 2;
}
return my_sum;
}
方式2:
每次划分2大组,分为发送方和接收方,最终发送至P0
int Global_sum(int my_int, int my_rank, int comm_sz, MPI_Comm comm)
{
int dest, src;
int recvtemp;
int cur_comm_sz;
int my_sum = my_int;
cur_comm_sz = comm_sz;
while (cur_comm_sz > 1 && my_rank < cur_comm_sz)
{
if (my_rank >= cur_comm_sz / 2) {
dest = my_rank - cur_comm_sz / 2;
MPI_Send(&my_sum, 1, MPI_INT, dest, 2, MPI_COMM_WORLD);
return 0;
}
else {
src = my_rank + cur_comm_sz / 2;
MPI_Recv(&recvtemp, 1, MPI_INT, src, 2, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
my_sum += recvtemp;
}
cur_comm_sz /= 2;
}
return my_sum;
}