I am trying to apply MPI_Reduce with MPI_SUM operation. There are 12 processes. Using MPI_Comm_split I get 4 communicators by 3 processes.
Each process produces a value and sends the result to all other processes in the group. As a result, it is necessary to find the sum of the values for each group.
My code:
#include <iostream>
#include <cstdlib>
#include "mpi.h"
using namespace std;
int main(int argc, char** argv)
{
int sum_score, player_score;
MPI_Status status;
MPI_Init(&argc, &argv);
int world_rank, world_size;
MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
MPI_Comm_size(MPI_COMM_WORLD, &world_size);
int players = world_rank / 4;
MPI_Comm team_comm;
MPI_Comm_split(MPI_COMM_WORLD, players, world_rank, &team_comm);
int team_rank, team_size;
MPI_Comm_rank(team_comm, &team_rank);
MPI_Comm_size(team_comm, &team_size);
std::srand(world_rank);
player_score = team_rank+1; // Some value
printf("Team %d, player %2d, score %d \n", team_rank + 1, world_rank + 1, player_score);
for (int i=0; i<world_size;++i) {
MPI_Reduce(&player_score, &sum_score, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
}
if (world_rank == 0)
cout << "Sum " << sum_score << endl;
MPI_Comm_free(&team_comm);
MPI_Finalize();
return 0;
}
I've tried many useless for
s and if
s. And used MPI_Reduce as
MPI_Reduce(&player_score, &sum_score, 1, MPI_INT, MPI_SUM, team_rank, team_comm);
But for now, it's only possible to summarize the results of all processes, not separately by groups.
What needs to be done to summarize the values within each group separately? I expect:
Team 1: sum 11
Team 2: sum 26
Team 3: sum 24
Team 4: sum 28
My console for now:
mpiexec -np 12 Project1.exe
Team 1, player 1, score 1
Sum 30
Team 3, player 3, score 3
Team 2, player 6, score 2
Team 1, player 5, score 1
Team 2, player 10, score 2
Team 2, player 2, score 2
Team 4, player 4, score 4
Team 3, player 11, score 3
Team 1, player 9, score 1
Team 4, player 8, score 4
Team 4, player 12, score 4
Team 3, player 7, score 3