1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
|
#include "iostream"
#include "mpi.h"
#include "vector"
#include <stdio.h>
#include <stdlib.h>
typedef std::vector<int> vecint;
typedef std::vector<vecint> vecvecint;
void my_reduce_function(void* inputBuffer, void* outputBuffer, int *len, MPI_Datatype* datatype)
{
int myrank, num_procs;
MPI_Comm_rank(MPI_COMM_WORLD, &myrank);
MPI_Comm_size(MPI_COMM_WORLD, &num_procs);
vecvecint* input = (vecvecint*)inputBuffer;
vecint* output = (vecint*)outputBuffer;
//input[0]=local result
//input[1]=local2global
//input[2]=global2local
//input[3]=mpi_repetition
for (int proc = 0; proc < num_procs; proc++) {
if (myrank == proc) {
for (int i = 0; i < (*input)[1].size(); i++)
{
(*output)[(*input)[1][i]] += ((*input)[0][(*input)[2][(*input)[1][i]]])/(*input)[3][(*input)[1][i]];
}
}
MPI_Barrier(MPI_COMM_WORLD);
}
}
int main(int argc, char* argv[])
{
int myrank,num_procs;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &myrank);
MPI_Comm_size(MPI_COMM_WORLD, &num_procs);
int root_rank = 0;
vecvecint data;
//if (num_procs != 2)
//{
// printf("This application is meant to be run with 2 processes.\n");
// MPI_Abort(MPI_COMM_WORLD, EXIT_FAILURE);
//}
for (int proc = 0; proc < num_procs; proc++) {
if (proc == 0) {
data = { { 1,3,4 },{ 0,1,2 },{ 0,1,2,-1},{ 2,1,2,1 } };
}
else {
data = { { 2,5,6 },{ 0,2,3 },{ 0,-1,1,2 },{ 2,1,2,1 } };
}
}
MPI_Op operation;
int len = 4;
MPI_Op_create(&my_reduce_function, 1,&operation);
vecint reduction_results;
MPI_Reduce(&data, &reduction_results, len, MPI_INT, operation, root_rank, MPI_COMM_WORLD);
if (myrank == root_rank)
{
printf("The sum of first elements of data is %d.\n", reduction_results[0]);
printf("The sum of second elements of data is %d.\n", reduction_results[1]);
printf("The sum of second elements of data is %d.\n", reduction_results[2]);
printf("The sum of second elements of data is %d.\n", reduction_results[3]);
}
MPI_Op_free(&operation);
MPI_Finalize();
return EXIT_SUCCESS;
}
|